Is it possible that TreeSet equals HashSet but not HashSet equals TreeSet
Your interviewer is right, they do not hold equivalence relation for some specific cases. It is possible that TreeSet
can be equal to HashSet
and not vice-versa. Here is an example:
TreeSet<String> treeSet = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
HashSet<String> hashSet = new HashSet<>();
treeSet.addAll(List.of("A", "b"));
hashSet.addAll(List.of("A", "B"));
System.out.println(hashSet.equals(treeSet)); // false
System.out.println(treeSet.equals(hashSet)); // true
The reason for this is that a TreeSet
uses comparator to determine if an element is duplicate while HashSet
uses equals
.
Quoting TreeSet
:
Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface.
It’s not possible without violating the contract of either equals or Set. The definition of equals in Java requires symmetry, I.e. a.equals(b)
must be the same as b.equals(a)
.
In fact, the very documentation of Set says
Returns true if the specified object is also a set, the two sets have the same size, and every member of the specified set is contained in this set (or equivalently, every member of this set is contained in the specified set). This definition ensures that the equals method works properly across different implementations of the set interface.
NO, this is impossible without violating general contract of the equals method of the Object
class, which requires symmetry, i. e. x.equals(y)
if and only if y.equals(x)
.
BUT, classes TreeSet
and HashSet
implement the equals contract of the Set
interface differently. This contract requires, among other things, that every member of the specified set is contained in this set. To determine whether an element is in the set the contains
method is called, which for TreeSet uses Comparator
and for HashSet uses hashCode
.
And finally:
YES, this is possible in some cases.