2

我正在寻找一种在java中的本地方式(最好)来实现一个数据结构来保存一个int作为键和一组键/值对作为值。本质上 if 将是索引引用的字典数组。

前任:

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

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

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

4

4 回答 4

4
  • 如果您事先知道字典的数量,那么最小结构是 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);    
    
于 2013-05-29T03:44:42.550 回答
2

地图怎么样

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

一个具体的实现是HashMap

于 2013-05-29T03:11:35.890 回答
0

这里看看HashMaps

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

我想这就是你要找的

于 2013-05-29T03:11:19.423 回答
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
于 2013-05-29T03:25:32.857 回答