Object.hashCode() VS Map.get(key)

探讨了在使用HashMap时,若作为键值的集合对象被修改,会导致其哈希码发生变化,进而引发原本存在的键值对查询失效的问题。文章通过示例说明了这一现象,并强调了在设计时选择不可变类型作为键的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

map.get(key)时,key最好是只读的对象。


        因为 Object.hashCode()的JDK文档提到过:the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. 下面是例证:

  List list = new ArrayList();
  Map map = new HashMap();
  map.put(list, "aaa");
  System.out.println(map.get(list)); //aaa
  list.add("bbb");
  System.out.println(map.get(list)); //null, 如此不妥,因为hashcode变了。


 Object.hashCode() 文档表明:hashCode()方法的本意是为hashtable算法服务。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值