2014-10-05 94 views
0

我有以下兩種HashMaps其中Student是我創建的對象,並且具有Student(String, String)返回嵌套散列映射

static HashMap<String, Student> hashMap = new HashMap<>(); 
static HashMap<String, HashMap<String, Student>> finalHashMap = new HashMap<>(); 

我創建了以下Students,並將它們加入到hashMapfirstName作爲Key

格式
Student st1 = new Student("julian", "rogers"); 
Student st2 = new Student("jason", "Smith"); 

hashMap.put("julian", st1); 
hashMap.put("jason", st2); 

然後我加hashMapfinalHashMap的第一個字母firstName作爲key

finalHashMap.put("j", hashMap); 

我怎樣才能返回與關鍵j HashMap的?

我試着創建一個新的hashmap並使用get()但它沒有工作。我得到一個null pointer exception

static HashMap<String, Student> hashMapTemp = new HashMap<>(); 
hashMapTemp.putAll(finalHashMap.get('j')); 

for (String key : hashMapTemp.keySet()) 
{ 
    System.out.println(key + " " + hashMapTemp.get(key)); 
} 

輸出

java.lang.NullPointerException 
    at java.util.HashMap.putAll(Unknown Source) 

注:我嘗試使用put(),也得到了同樣的錯誤。

+0

你在哪裏得到NPE? – 2014-10-05 17:15:56

+0

爲什麼你將結果添加到'hashMapTemp'而不是隻是說'for(String key:finalHashMap.get(「j」))'? – Krease 2014-10-05 17:18:24

+0

作爲一個說明,如果將它作爲一個自包含的類來演示問題而不是一堆代碼片段,將來可能更容易解析這樣的事情。 – Krease 2014-10-05 17:19:54

回答

2

hashMapTemp.putAll(finalHashMap.get('j'));

我想這應該是:

hashMapTemp.putAll(finalHashMap.get("j"));

你在finalHashMap鍵是一個字符串,而不是一個字符。

0
hashMapTemp.putAll(finalHashMap.get('j')); 

這條線有點奇怪,你尋找一個字符而不是字符串(如你所定義的)。 考慮使用static HashMap<Character, Student> finalHashMap = new HashMap<>()

-1
public static HashMap<String, Student> find(String key, HashMap<String, HashMap<String, Student>> dataMap) { 
    HashMap<String, Student> result = null; 
    for (String s : dataMap.keySet()) { 
     if (s.equalsIgnoreCase(key)) { 
      result = dataMap.get(s); 
      break; 
     } 
    } 
    return result; 
} 

然後只需要調用像這樣的方法:

HashMap<String, Student> result = find("j", finalHashMap); 
+0

使用HashMap的一個要點是什麼?它提供了一種O(1)查找方法,如果要找到一個基於某個鍵的值,在所有鍵上進行迭代,直到找到所需的一個鍵,使其成爲O(n)? – 2014-10-05 17:29:24