我在java的一個HashMap中,我存儲測試:遍歷HashMap中返回值「空」
HashMap<String, String> hmap = new HashMap<Integer, String>();
//add elements to HashMap
hmap.put("1", "AA");
hmap.put("2", "BB");
hmap.put("3", "CC");
hmap.put("4", "DD");
然後我想組我的鍵值通過對
for(String id1: hmap.keySet()) {
Integer id2 = Integer.valueOf(id1)+1;
while(id2 <= 4){
String IDs = id1 + "/" + String.valueOf(id2);
String Contents = hmap.get(id1) + "/" + hmap.get(String.valueOf(id2));
System.out.println(IDs);
System.out.println(Contents);
id2++;
}
}
但我得到的結果:
1/2
AA/null
1/3
AA/null
1/4
AA/null
2/3
BB/null
2/4
BB/null
3/4
CC/null
雖然我希望
1/2
AA/BB
1/3
AA/CC
...
我張貼的代碼只是舉例。我有一個帶有(ID,值)的HashMap,我想創建一個新的HashMap,其中包含所有ID(每次一對)和值對。但是hmap.get(String.valueOf(id2))總是返回一個「null」值。
有人可以解釋爲什麼第二個值爲空,我能做些什麼來補救?
輸出結果應該是什麼樣子? –
你的HashMap是一個整數 - >字符串映射,你爲什麼在你的代碼中使用String作爲鍵類型? –
您的密鑰類型是整數。你不應該有String.valueOf(id2),因爲它創建了一個字符串類型,並且沒有默認的方法將它轉換爲查找的整數。只要做hmap.get(id2)。 – user1676075