我今天接受了采访,接受我采访的人对他的陈述感到困惑,询问是否有可能 TreeSet
等于 HashSet
但不是 HashSet
等于 TreeSet
.我说“不”,但据他说,答案是"is"。
怎么可能?
最佳答案
你的面试官是对的,他们在某些特定情况下没有等价关系。可能是 TreeSet
可以等于 HashSet
反之亦然。下面是一个例子:
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
.报价
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.
关于java - TreeSet 是否可能等于 HashSet 但 HashSet 不等于 TreeSet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62477034/