字典条目数组的数据结构

Joh*_*aum 3 java

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

前任:

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

foo.put[["hello", "world"], ["so","rocks"]]
Run Code Online (Sandbox Code Playgroud)

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

Gle*_*est 6

  • 如果您事先知道字典的数量,那么最小结构是 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
    
    Run Code Online (Sandbox Code Playgroud)
  • 但更灵活的结构是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);    
    
    Run Code Online (Sandbox Code Playgroud)