我正在 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"
最佳答案
如果你事先知道字典的数量,那么最小结构是 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);
关于java - 字典条目数组的数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16804830/