Why does get get null if "two instances occur with a hash with the same bucket"? What is the role (not getting the right instance) of the HashMap optimization "which uses ..."?
Key offer
[...] does not require checking the equality of the object if the hash codes do not match.
Thus, even if the key hash is in the same bucket, .equals may not be called (due to caching optimization) for the corresponding element (since even the hash codes do not match). Thus, even if the corresponding element is in the same bucket, it can never be compared using .equals and therefore cannot be "found".
Just for the case - "two instances occur with a hash with the same bucket" - what if the HashMap is worried about "equality of the object if the hash codes do not match"?
If he did not have this optimization and actually checked .equals on all elements of the corresponding bucket, and if two hashes hit the hash in the same bucket, then get-method will return the correct element. (But that would be pure luck, because if the objects are not equal, then there is no guarantee that these two hashes will be displayed in the same bucket in the first place.)
source share