Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data Structure for an array of Dictionary entries

Tags:

java

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"

like image 220
John Baum Avatar asked Jan 29 '26 02:01

John Baum


1 Answers

  • 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);    
    
like image 125
Glen Best Avatar answered Jan 30 '26 16:01

Glen Best