java - TreeSet 和 equals 函数

标签 java equals comparator treeset

有一个 Java bean 对象根据特定标准(标准 A)实现了 equals 功能。我需要根据另一个标准(标准 B)识别唯一对象。由于 equals 函数使用条件 A,我不能使用 HashSet。所以我考虑将 TreeSet 与基于条件 B 的自定义 Comparator 一起使用。我的问题是,是否允许这样做?这种方法有什么问题吗?

谢谢。

最佳答案

这是 Oracle Java 的一些指南:

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. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

我认为在技术方面,不,你没有任何问题。但是,在编码、可读性和可维护性方面,你必须小心,因为其他人可能会误用或误解你在做什么

关于java - TreeSet 和 equals 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3655504/

相关文章:

java - PriorityQueue 的意外行为删除 : Why isn't compareTo used?

java - 对集合使用 hashCode() 和 equals() 的多个替代方案

java - 具有内部比较器类的 PriorityQueue

java - spring boot scheduler 服务的负载均衡

java - MyVD 的自定义 LDAP 绑定(bind)插入

java - 从套接字读取时如何检测客户端何时完成发送请求?

scala - scala DSL 中的final == 和!=(等于和不等于)方法的解决方法

java - 为什么 Double::compareTo 可以作为 Stream.max(Comparator<?super T>comparator) 的参数

c - C 中的 string_comparator

java - 如何维持一对一的关系? (无框架)