HashSet workaround for changing internal object

The answer to this question explains the problem I am facing: HashSet.remove () and Iterator.remove () do not work

Basically, as soon as I add something to the HashSet, if I change any of its fields, then the set will not give any equality tests with the set containing the object with exactly the same fields, since the hash code in which it was saved if it had different fields set.

So, since this answer explains what happens, would it be a good workaround to have both the uniqueness of using the set and the ability to change the internal fields of the objects in the set? Or is it simply impossible?

+5
source share
5 answers

Remove the object you want to modify from the set, modify it, and then add it back. As far as I know, there is no standard implementation Setthat can handle fields (which are used in the implementation hashCode()or compareTo()) that change when saved.

Alternatively, if the fields are not used to determine identity, equality or location (i.e. are not used in hashCode(), compareToor equals()), then there is no problem.

+5
source

If the fields you change are not part of the equality test, they should not be part of the hash code calculation either. In this case, there is no problem: you can simply change these fields.

, , , , .

, , .

+7

- hashCode(), . , , System.identityHashCode(). hashCode() . , , , .

+3

HashMap HashSet. , .

+1
source

Use any other collection (possibly LinkedList) and check the uniqueness only at the time of adding, for example, in

public class MySetList<E> extends LinkedList<E> implements Set<E> {
    private static final long serialVersionUID = 1L;

    @Override
    public boolean add(E e) {
        return new HashSet<E>(this).add(e) ? super.add(e) : false;
    }
}
-1
source

All Articles