HashMap 优化的影响,该优化将与每个条目关联的哈希码缓存到其 get 方法
摘自第 46 页“有效的 Java”Joshua Bloch。第 9 项:当您重写 equals 时,始终重写 hashCode
- 某些类 PhoneNumber 重写 equals() 但不重写 hashCode()
- “涉及两个实例:一个用于插入 HashMap,第二个 equal 实例用于(尝试)检索。” ... “...即使两个实例碰巧散列到同一个存储桶,get方法几乎肯定会返回null,因为HashMap有一个缓存散列码的优化与每个条目相关联,如果哈希码不匹配,则不会检查对象相等性。”
问题是 - 如果“两个实例碰巧散列到同一个存储桶”,为什么“get”将返回“null”?
“兑现...”的 HashMap 优化的作用是什么(在没有获得正确的实例中)?
“仅针对这种情况 - “两个实例碰巧散列到同一个存储桶” - 如果 HashMap 担心“如果散列码不匹配,则对象相等”怎么办?
from p.46 "Effective Java" Joshua Bloch. Item 9: ALways override hashCode when you override equals
- Some class PhoneNumber overrides equals() and doesn't override hashCode()
- "two instances are involved: one is used for insertion into the HashMap, and a second, equal, instance is used for (attempted) retrieval."
...
"... Even if the two instances happen to hash to the same bucket, the get method will almost certainly return null , as HashMap has an optimization that caches the hash code associated with each entry and doesn't bother checking for object equality if the hash codes doesn't match."
The questions is
- why 'get' will return 'null' if "the two instances happen to hash to the same bucket"?
what is the role (in not getting the right instance) of the HashMap optimization "that cashes..."?
Just for the case - "the two instances happen to hash to the same bucket"- what if HashMap bothers about "object equality if the hash codes doesn't match"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
关键句子是
因此,即使键哈希到同一个存储桶,
.equals
也可能不会为相关元素调用(由于缓存优化)(因为甚至哈希码都不匹配)。因此,即使相关元素位于同一个存储桶中,也可能永远不会通过.equals
进行比较,从而无法“找到”。如果没有” t有这种优化,并且实际上确实检查了相应存储桶中所有元素的
.equals
并且如果两个哈希碰巧发生hash 到同一个桶,那么 get 方法将返回正确的元素。 (但这纯粹是运气,因为如果对象不相等,则不能保证两个哈希值首先会映射到同一个存储桶。)The key sentence is
So even if the keys hash to the same bucket,
.equals
may not be invoked (due to the caching optimizations) for the relevant element (since not even the hash-codes matches). Thus, even if the relevant element resides in the same bucket, it may never be compared through.equals
, and thus not "found".If it didn't have this optimization, and actually did check
.equals
on all elements in the corresponding bucket and if the two hashes happened to hash to the same bucket, then the get-method would return the correct element. (But this would be pure luck, since if the objects aren't equal, then there is no guarantee that the two hashes will map to the same bucket in the first place.)只有当 hashCode 不相等时才会这样做。它可以这样做是因为根据 hashCode() 的约定,不相等的 hashCode 意味着不相等的对象。(请注意,反之则不然:语言律师请注意。)
It will only do that if the hashCodes are unequal. It can do that because by the contract of hashCode(), unequal hashCodes imply unequal objects. (Note that the reverse isn't true: language lawyers please note.)