I am looking for a native way (preferably) in java to implement a data structure to hold an int as key and a set of key/value pair as the value. In essence if would be an array of dictionaires referenced by an index.
Ex:
MyDataStructure[[Key,Value]] foo = new ...
foo.put[["hello", "world"], ["so","rocks"]]
println(foo[0].getValue("hello")) would print out "world" and println(foo[0].getValue("so")) would print out "rocks"
If you know in advance number of dictionaries, then minimum structure is array of 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
But a more flexible structure is List<Map<Key,Value>>, because number of dictionaries can change dynamically. Any List will work - but in your case, ArrayList would be best for fast access (get) by index:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With