HashSet.remove() and Iterator.remove() not working

前端 未结 10 1496
借酒劲吻你
借酒劲吻你 2020-12-13 00:32

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

10条回答
  •  [愿得一人]
    2020-12-13 01:00

    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.

提交回复
热议问题