Imagine we have this piece of code.
public class HashAddAfter { private class A { public int value; public A(int value) { this.value = value; } public void setValue(int value) { this.value = value; }
I did not put the code for hashCode () and equals () due to space limitations, but this is the one that was created from Eclipse.
The problem is that before changing the elements in the two sets, the sets are equal. After changing their values ββ(each by the same value), the sets are no longer equal, although e1.hashCode () == e2.hashCode () and e1.equals (e2).
I assume that when comparing two HashSets, Java uses the source hash code of the element (the one that is at the time of insertion). Thus, changing elements after insertion changes the original hash code and therefore contains () returns false.
In my opinion, this is a very unintuitive behavior.
What do you think?
source share