什么對象可以作為HashMap的key值?
從HashMap的語法上來講,一切對象都可以作為Key值。如:Integer、Long、String、Object等。但是在實際工作中,最常用的使用String作為Key值。
原因如下:
1.使用Object作為Key值的時候,如Class Person (里面包含,姓名,年齡,性別,電話等屬性)作為Key。當Person類中的屬性改變時,導致hashCode的值也發生變化,變化后,map.get(key)因為hashCode值的變化,而無法找到之前保存的value值,同樣,刪除也取不到值。
解決方案是重寫HashCode方法
2.避免使用Long,Integer做key。有一次項目里排查bug,最后發現這個坑,由於拆箱裝箱問題,導致取不到數據。
1 Map<Integer, String> map1 = new HashMap<Integer, String>(); 2 map1.put(11, "11"); 3 map1.put(22, "22"); 4 long key1 = 11; 5 System.out.println(map1.get(key1)); // null 6 7 Map<Long, String> map2 = new HashMap<Long, String>(); 8 map2.put(11L, "11"); 9 map2.put(22L, "22"); 10 int key2 = 11; 11 System.out.println(map1.get(key2)); // 11
關於拆箱裝箱,大家可以運行下面代碼,嘗試一下。類似下面代碼的操作應該極力避免。
1 Integer a = 1; 2 Integer b = 2; 3 Integer c = 3; 4 Integer d = 3; 5 Integer e = 321; 6 Integer f = 321; 7 Long g = 3L; 8 System.out.println(c == d); 9 System.out.println(e == f); 10 System.out.println(c == (a+b)); 11 System.out.println(c.equals(a+b)); 12 System.out.println(g == (a+b)); 13 System.out.println(g.equals(a+b));
所以,綜上所述,最好使用String來作為key使用。