I\'m having problems with Iterator.remove() called on a HashSet.
I\'ve a Set of time stamped objects. Before adding a new item to the Set, I loop through the set, i
You should all be careful of any Java Collection that fetches its children by hashcode, in the case that its child type's hashcode depends on its mutable state. An example:
HashSet> or HashSet> or HashMap variant:
HashSet retrieves an item by its hashCode, but its item type is a HashSet, and hashSet.hashCode depends on its item's state.
Code for that matter:
HashSet> coll = new HashSet>();
HashSet set1 = new HashSet();
set1.add("1");
coll.add(set1);
print(set1.hashCode()); //---> will output X
set1.add("2");
print(set1.hashCode()); //---> will output Y
coll.remove(set1) // WILL FAIL TO REMOVE (SILENTLY)
Reason being is HashSet's remove method uses HashMap and it identifies keys by hashCode, while AbstractSet's hashCode is dynamic and depends upon the mutable properties of itself.