字典条目数组的数据结构

时间:2013-05-29 03:08:26

标签: java

我正在寻找java中的本地方式(最好)来实现一个数据结构来保存一个int作为键,一组键/值对作为值。本质上,如果是由索引引用的一系列词典。

例如:

MyDataStructure[[Key,Value]] foo = new ...

foo.put[["hello", "world"], ["so","rocks"]]

println(foo[0].getValue("hello"))会打印出"world"println(foo[0].getValue("so"))会打印出"rocks"

4 个答案:

答案 0 :(得分:3)

  • 如果事先知道字典数,那么最小结构就是Map的数组:

    Map<Key,Value>[] dictonaires = new HashMap<Key,Value>[20];
    for (int i=0; i<dictionaries.length; i++) {
        dictionaries[i] = new Hashmap<Key,Value>();
    }
    
    // Any time later, refer to a dictionary by index 
    Map<Key,Value> currentDictionary = dictionaries[10];
    // Can call currentDictionar.put/get/remove to create or update/read/delete 
    // entries, but can't add/remove entire dictionaries
    
  • 但更灵活的结构是List<Map<Key,Value>>,因为字典数量可以动态变化。任何List都可以使用 - 但在您的情况下,ArrayList最适合快速访问(获取)索引:

    List<Map<Key,Value>> dictionaryList = new ArrayList<Map<Key,Value>>();
    
    // Then add new dictionary anytime later:
    dictionaryList.add(new HashMap<Key,Value>());    
    
    // Access by index (index matches order of adding):
    Map<Key,Value> currentDictionary = dictionaryList.get(10);    
    // Can call currentDictionar.put/get/remove to create or update/read/delete 
    // entries, but can't add/remove entire dictionaries
    
    // Or even remove entire dictionary by index:
    dictionaryList.remove(10);    
    

答案 1 :(得分:2)

地图怎么样

Map<Integer, Map<Key, Value>> myMap;

具体实现是HashMap

答案 2 :(得分:0)

这里看看HashMaps

http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html

我认为这就是你要找的东西

答案 3 :(得分:0)

地图界面是您正在寻找的,具体实现:

    Map<Integer, Map<String, String>> map = new HashMap<>();
    Map<String, String> someInsert = new HashMap<>();
    someInsert.put("No", "Means no");
    map.put(0, someInsert);

    System.out.println(map.get(0).get("No"));

输出:

Means no