问题
I have classes like below
class A {
@Override
public boolean equals(Object other) { return true }
}
Class B extends A {
}
Class C extends A {
@Override
public boolean equals(Object other) { if ((other != null) || (other instanceOf B)) return false; }
}
In my main() I have this following code
Set<A> mySet = new CopyOnWriteArraySet<A>();
mySet.add(C);
I want mySet to contain C at this point
mySet.add(B); // #1
I want mySet to contain C & B at this point
mySet.remove(B); // #2
I want mySet to contain C at this point
I want to create a global queue where if object C exists in the queue B should be allowed to be added but not the other way around. So before #1 I am looping through the elements inside the set doing element.equals(B) with add on false.
But 1 is calling B.equals(C) which is returning true and so mySet has only one C object after this line
2 is again calling B.equals(C) which is returning true and removing the existing object C. Shouldn't it be C.equals(B) in this case? I am expecting this line as no-action
Is this some wrong use of CopyOnWriteArraySet?
Thanks for looking
回答1:
It is correct behavior it finds the element which is equal()
so it removes first element
Removes the specified element from this set if it is present. More formally, removes an element e such that
(o==null ? e==null : o.equals(e))
, if this set contains such an element. Returns true if this set contained the element (or equivalently, if this set changed as a result of the call). (This set will not contain the element once the call returns.) ...
回答2:
HashSet is the correct collection for my case. It won't call equals while adding elements unless there is hashCode match. That way I can still use my equals methods for my specific purpose.
来源:https://stackoverflow.com/questions/24920563/overriding-equals-for-copyonwritearrayset-add-and-remove