Java 字典项数组的数据结构

Java 字典项数组的数据结构,java,Java,我正在寻找一种java原生方法(最好是)来实现一个数据结构,将int作为键,将一组键/值对作为值。本质上,if是一个索引引用的词汇表数组 例: println(foo[0].getValue(“hello”)将打印出“world”,println(foo[0].getValue(“so”)将打印出“rocks”,这里看一下hashmap 我想这就是你要找的地图怎么样 Map<Integer, Map<Key, Value>> myMap; Map-myMap; 一个

我正在寻找一种java原生方法(最好是)来实现一个数据结构,将int作为键,将一组键/值对作为值。本质上,if是一个索引引用的词汇表数组

例:


println(foo[0].getValue(“hello”)
将打印出
“world”
println(foo[0].getValue(“so”)
将打印出
“rocks”
,这里看一下hashmap

我想这就是你要找的

地图怎么样

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

一个具体的实现是
HashMap

映射接口就是您要寻找的,它似乎是一个特定的实现:

    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"));
  • 如果您事先知道字典的数量,则最小结构是映射数组:

    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
    

考虑一张地图。Pair只是一个简单的java类。它将比使用一个完整的映射来存储一个简单的名称、值对更有效……所以我只是自己实现了pair类,对吗?只有一个构造函数和两个字段?这比Map之类的解决方案更有效?我有点惊讶,没有简单的方法来创建一个包含字典的数组。我来自Objective-C,这样做很简单,是的,会的。Pair只是一个建议,使用有意义的全名和有意义的全域。你当然可以用两个元素的数组。但是,当有更多更好的条款存在时,这看起来相当丑陋,你不觉得吗?为什么要访问带有索引的元素?如果你能消除这一点,你将能够在没有任何定制的情况下使用映射。像Pair这样的简单对象不会对性能产生影响。所以即使在安卓系统中,我也不会担心这个问题。是的,但是如果您只想为特定的键获取一个值,那么索引有什么用呢?让你的代码复杂化以获得感知到的性能增益绝非明智之举,因此我建议你采用这种方法,除非你对代码进行分析,并发现这是性能受损的地方(可能性很小)。这会有多高的效率?@JohnBaum评估此建议是你工作的一部分,而不是来自Mekswoll。
Means no
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>> 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);