什么对象可以作为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
System.out.println(map2.get(key2)); // null
关于拆箱装箱,大家可以运行下面代码,尝试一下。类似下面代码的操作应该极力避免。
Integer a = 1;
Integer b = 2;
Integer c = 3;
Integer d = 3;
Integer e = 321;
Integer f = 321;
Long g = 3L;
System.out.println(c == d);
System.out.println(e == f);
System.out.println(c == (a+b));
System.out.println(c.equals(a+b));
System.out.println(g == (a+b));
System.out.println(g.equals(a+b));
所以,综上所述,最好使用String来作为key使用。