今天在使用HashMap的时候,发现了一个奇怪的情况,通过map的get方法,拿不到对应的值,排查发现是由于Map的key类型是Integer,然后我传进去的是Long类型的。但是因为get方法没有值校验,再加上我以为这个地方比较的时候会自动拆箱,从而导致了这个问题。例子如下:
public class HelloWorld {
public static void main(String []args) {
Map<Integer,String> map = new HashMap<>();
Integer a = new Integer(20200601);
map.put(a,"六一");
Long b = new Long(20200601);
System.out.println(map.get(b));
}
}
因为get方法传参是Object类型,系统编译的时候也不会做校验,所以错误比较隐晦,debug时才发现,将Long类型拆箱成int值就好使了。
public class HelloWorld {
public static void main(String []args) {
Map<Integer,String> map = new HashMap<>();
Integer a = new Integer(20200601);
map.put(a,"六一");
Long b = new Long(20200601);
System.out.println(map.get(b.intValue()));
}
}