The impact of HashMap optimization, which caches the hash code associated with each record, with its get method

from p. 46 "Effective Java" by Joshua Bloch. Item 9: always cancels the hash code when you override equal

  • Some PhoneNumber class overrides equals () and does not override hashCode ()
  • "Two instances are involved: one is used to insert into the HashMap, and the second, an equal instance, is used to (attempt) a search." ... "... Even if both instances fall into the hash in the same bucket, the get method will almost certainly return null , because the HashMap has an optimization that caches the hash code associated with each record, t check if the object is equal if hash codes do not match. "

Questions - why does "get" return "null" if "two instances occur with a hash with the same bucket"?

  • What is the role of (not getting the right instance) HashMap optimization, "which uses ..."?

  • 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"?

+4
source share
2 answers

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.)

+4
source

why 'get' will return 'null' if "two cases happen with a hash with the same bucket"

This will only do this if the hash codes are unequal. He can do this because, under the hashCode () contract, unequal hash codes imply unequal objects. (Note that the opposite is not true: language lawyers should be aware.)

+1
source

All Articles