Why a HashSet Loses an Object After One Of Its Fields Changes

A Java example stores a Point in a HashSet, then changes its x field after insertion. Afterward, contains() and remove() both fail, even though the object is still physically inside the set. The cause is that HashMap picks a bucket from the hashCode at insertion time and does not re-bucket when the field changes, so lookups search the wrong bucket. As a result, a new Point with equal values can be added as a duplicate. The article notes that the Set contract leaves this behavior unspecified, and that the observed results come from running the code on OpenJDK 21.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.


Discussion (0)
Log in to join the discussion and vote.
Log in