java - TreeSet 是否可能等于 HashSet 但 HashSet 不等于 TreeSet

标签 java collections hashset treeset

我今天接受了采访,接受我采访的人对他的陈述感到困惑,询问是否有可能 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/

相关文章:

java - SVNKit 使用 auth 文件夹

java - Selenium Grid 并行测试不能并行工作

java - 调用 hashSet.clear() 后创建一个新的 HashSet 还是重用更好

java - 加速 HashSet 和 HashMap 性能

java - HashSet vs ArrayList 包含性能

从 servlet 返回到 JSP 时,Javascript 更改消失

Java 集合 : TreeMap. size() 和 TreeSet.size() : O(1) or O(n)?

java - 此 Java 代码中有多少对象符合垃圾回收条件?

java - 从列表转换为集合

java - 在开始迭代之前检查 Java 集合是否为空有用吗?