TreeSet 是否可能等于 HashSet 但 HashSet 不等于 TreeSet [英] Is it possible that TreeSet equals HashSet but not HashSet equals TreeSet
问题描述
我今天接受了一次采访,接受我采访的人对他的陈述感到困惑,他问TreeSet
是否可能等于 HashSet
但不等于 HashSet
等于 TreeSet
.我说不"但据他说,答案是是".
I had a interview today and the person taking my interview puzzled me with his statement asking if it possible that TreeSet
equals HashSet
but not HashSet
equals TreeSet
. I said "no" but according to him the answer is "yes".
怎么可能?
推荐答案
你的面试官是对的,他们在某些特定情况下不存在等价关系.TreeSet
可能等于 HashSet
,反之亦然.下面是一个例子:
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
这样做的原因是 TreeSet
使用比较器来确定元素是否重复,而 HashSet
使用 equals
.
The reason for this is that a TreeSet
uses comparator to determine if an element is duplicate while HashSet
uses equals
.
引用TreeSet
:
注意集合维护的顺序(无论是否提供显式比较器)必须与 equals 一致,才能正确实现 Set 接口.
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.
这篇关于TreeSet 是否可能等于 HashSet 但 HashSet 不等于 TreeSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!