gpt4 book ai didi

java - TreeSet 和 equals 函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:10:42 24 4
gpt4 key购买 nike

有一个 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/

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