在Java中,Map里面的鍵和值可以為空嗎?我們先來看一個例子:
private static void TestHashMap() {
// TODO Auto-generated method stub
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(0, "0");
map.put(1, null);
map.put(null, "2");
map.put(3, "");
map.put(null, "4");
for (Integer key : map.keySet()) {
System.out.println("Key-->" + key + " Value-->" + map.get(key));
}
}
輸出結果:
Key–>null Value–>4
Key–>0 Value–>0
Key–>1 Value–>null
Key–>3 Value–>
由此看來,對於我們平時使用較多的HashMap來說,鍵和值是可以為null的,map.put(null, “4”)還會覆蓋map.put(null, “2”)這個操作。
我們是否可以由此得出Map里面的鍵和值是否一定可以為null呢?並不一定,再來看一個例子:
private static void TestHashTable() {
// TODO Auto-generated method stub
Map<Integer, String> map = new Hashtable<Integer, String>();
map.put(0, "0");
map.put(1, null);
map.put(null, "2");
map.put(3, "");
map.put(null, "4");
for (Integer key : map.keySet()) {
System.out.println("Key-->" + key + " Value-->" + map.get(key));
}
}
運行之后,會出現“NullPointerException”異常。
查看Java Api,可以看到:


所以,對於Map里面的鍵和值是否可以為空的問題,答案是:不一定。對於HashMap來說,可以存放null鍵和null值,而HashTable則不可以。
對於HashMap和HashTable的區別,可以參考:
https://my.oschina.net/u/1458864/blog/267591
更多思考:
對於第一個例子,我們會發現一個問題:打印HashMap的鍵和值的時候,輸出結果並不是按照我們的插入順序輸出的。很多時候我們希望怎么放進去,就怎么拿出來,這種順序對於顯示或者處理很重要。查看Api后,發現ListOrderedMap可以滿足我們的要求,感興趣的同學可以自己試一下。
