gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:28:10 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com