引言
在刷leetcode时,遇到的离谱问题,需要依靠map的返回值来判断 是否重复.自己看半天没敢怀疑是map. 最后一个三级大佬提出的这个问题,被一个5级大佬解决了.太牛了!
正文
如果该key是第一次插入,那么返回null.这个一点问题没有
但如果是重复添加相同的key,那么问题就来了.返回的是原本key上对应的包装类型对象(地址+值).
@Test
public void test() {
//HashMap<int, int> int不允许. map中键值必须是包装类型
HashMap<Integer, Integer> map = new HashMap<>();
Integer a = 11111;
map.put(1, a);
Integer a1 = map.put(1, 1); //返回对象地址@837
map.put(2, a);
Integer a2 = map.put(2, 1); //返回对象地址@837
System.out.println(a1==a2); //true 因为这边插入的是同一个Integer对象
map.put(3, 11111); //int 类型会自动包装为Integer 但是超过127就是新建对象了
Integer a3 = map.put(3, 1); //返回对象地址@839
map.put(4, 11111);
Integer a4 = map.put(4, 1); //返回对象地址@840
System.out.println(a3==a4); //false 虽然替换的值一样,但是11111是int类型,超过127就会重新创建Integer对象了
}