HashMap使用注意事项

在工作中碰到过一次HashMap的使用造成的Bug,觉得挺有意思。

 1 import java.util.HashMap;
 2 import java.util.Map;
 3 
 4 public class HashMapTest {
 5 
 6     public static void main(String[] args) {
 7 
 8         Map<Integer, String> map = new HashMap<>();
 9         map.put(0, "0");
10         map.put(1, "1");
11         map.put(2, "2");
12         map.put(3, "3");
13         map.put(4, "4");
14         for (short i = 0; i < 5 ; i++) {
15             System.out.println(map.get(i));;
16         }
17     }
18 }

上面代码输出全为null,为什么呢?

原因如下:

map的key为Integer类型,java中的数字常量默认为int,当往map里put内容时,key会从小写的int装箱成Integer对象。

HashMap中的get方法定义如下:

当15行调用map.get(i)时,因为i是short类型,会被自动装箱为Short对象。跟踪map.ge(Object key)方法继续往里走:

get方法首先拿到key的hashcode,然后跟数组表长度-1相与得到索引位置,将索引位置存储的Node中的key的

hashcode与传入key的hashcode作比较,并且比较key的内存地址或者key是否equals。

这个地方可以清楚看到,Map中Node存储的key为Integer对象,我们传入的key为Short对象,虽然两者的hashcode是一样的,当无论== 还是equals都不相等,所以无法拿到Node中的value。

扫描二维码关注公众号,回复: 3640953 查看本文章

总结:

1、hashcode一样,对象不一定相同(无论内存地址还是逻辑内容)。

2、对于泛型集合装基本数据类型时,要注意装箱问题。

猜你喜欢

转载自www.cnblogs.com/fly1024/p/9820854.html