Machine-translated by Google. Questions are authored in English.
Top

Discussion

Which of these statements about using a mutable object as a HashMap key and then changing it is correct?

  • A.The map re-hashes the entry automatically when the key changes.
  • B.The change is rejected.
  • C.The entry remains reachable.
  • D.The entry may become unreachable.

Answer: D

A hash table finds a bucket from the key's hash code and only then compares with equals. If the field that hashCode depends on is changed after insertion, a later lookup computes a different bucket and finds nothing, while the entry still occupies the old one. Keys should be immutable, or at least stable in the fields hashCode reads.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.