Yes, it calls equals(). compareTo() could only be used if the Set knew that it contained Comparable objects (sorted sets, for instance, might possibly do this).
Yes, it calls equals(). compareTo() could only be used if the Set knew that it contained Comparable objects (sorted sets, for instance, might possibly do this).
It depends on the implementation.
For instance, a HashSet will use hashCode and equals. A TreeSet will probably use compareTo. Ultimately, so long as your types behave appropriately it shouldn't matter.
AtomicReference a = new AtomicReference<>("A");
AtomicReference a2 = new AtomicReference<>("A");
System.out.println(a==a2);
your answer lies within.
if instead of Object you use a custom class and you Override equals method it will work as expected.
to get this to work
class AtomicString{
private AtomicReference<String> s;
public AtomicString(String s) {
this.s = new AtomicReference<>(s);
}
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
AtomicString that = (AtomicString) o;
return this.s.get().equals(that.getS().get());
}
public AtomicReference<String> getS() {
return s;
}
@Override public int hashCode() {
return Objects.hash(s.get());
}
The problem really is the inconsistent "equality" logic. Both TreeSet and HashSet inherit AbstractSet#removeAll, which iterates over the smaller set, therefore using that set's object comparison. As it turns out, "equality" logic can be overridden using a TreeSet.
This is a problem that you can avoid by choosing one of the two Set implementations. If you choose TreeSet, then you must also use the same comparator.
You can't really use HashSet in this case because AtomicReference doesn't have an implementation of equals/hashCode that would work for you. So your only practical choice is to use TreeSet:
Comparator<Object> comparator = (a, b) -> a.toString().compareTo(b.toString());
final Set<Object> set1 = new TreeSet<>(comparator);
final Set<Object> set2 = new TreeSet<>(comparator);
This will break your current tests, but because elements are now being removed as they should (according to your comparator's logic).