java中使用Map时value存储具有常量池的基本数据类型(如Integer)遇到的问题
今天刷leetcode 242.有效的字母异位词用到了两个map,map的value为Integer类型,本以为代码天衣无缝,却有一个测试用例不能通过。究其原因,想到了Integer在-128到127有缓存。
import java.util.HashMap;
import java.util.Map;
public class Se {
public static void main(String[] args) {
Map<Integer, Integer> map1 = new HashMap<>();
Map<Integer, Integer> map2 = new HashMap<>();
map1.put(1, 1024);
map2.put(1, 1024);
map1.put(2, 127);
map2.put(2, 127);
System.out.println(map1.get(1) == map2.get(1));
System.out.println(map1.get(2) == map2.get(2));
System.out.println(map1.get(1) == map1.get(1));
}
}
输出结果如下
其他有缓存的包装类也会出现这种情况,希望能对大家有所帮助!