Overriding equals for CopyOnWriteArraySet.add and

2020-05-06 23:05发布

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

2条回答
贼婆χ
2楼-- · 2020-05-06 23:20

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.) ...

查看更多
可以哭但决不认输i
3楼-- · 2020-05-06 23:31

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.

查看更多
登录 后发表回答