HashMap 中 Key 类型的选择

什么对象可以作为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

关于拆箱装箱,大家可以运行下面代码,尝试一下。类似下面代码的操作应该极力避免。

 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使用。

 

posted @ 2020-03-08 18:56  Mr.袋鼠  阅读(11677)  评论(2编辑  收藏  举报