2013-05-29 56 views
1

我正在尋找一種原生的方式(最好)在java中實現一個數據結構來保存一個int作爲鍵和一組鍵/值對作爲值。本質上,如果將是由索引引用的一系列詞典。字典項數組的數據結構

例:

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

foo.put[["hello", "world"], ["so","rocks"]] 

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

+0

考慮一個地圖<整數,對<字符串,字符串>>。 Pair只是一個簡單的Java類。這將比使用整個Map來存儲簡單的名稱,值對更加高效... – Thihara

+0

所以我只是實現了對類自己正確?只有一個構造函數和兩個字段?而且這將比解決方案更有效率,比如地圖? –

+0

林有點驚訝沒有簡單的方法來創建一個擁有一本字典的數組。我來自Objective-C,並且很容易在那裏做 –

回答

1
  • 如果你在字典中的提前號碼百事通,然後最小結構是地圖數組:

    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);  
    
2

怎麼樣地圖

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

具體實現是HashMap

+0

這會是多高效? –

+0

@JohnBaum評估這個建議是你工作的一部分,而不是來自Mekswoll。 –

0

地圖界面是你在找什麼,似乎,具體的實現:

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")); 

日期:

Means no