是否有可能TreeSet等于HashSet但不等于HashSet等于TreeSet [英] Is it possible that TreeSet equals HashSet but not HashSet equals TreeSet

查看:89
本文介绍了是否有可能TreeSet等于HashSet但不等于HashSet等于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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆