且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

与集合相等且可比

更新时间:2022-05-07 23:23:45

看来这很好 TreeSet的JavaDoc href = code> (粗体显示):

It seems like this is pretty well documented in JavaDoc of TreeSet (bold mine):


请注意,该顺序由集合(无论是否是显式)维护如果要正确实现 Set 接口,则必须与equals 保持一致。 (有关与equals的精确定义,请参见可比较比较器。)因为 Set 接口是根据 equals 操作定义的,而 TreeSet 实例使用其 compareTo (或比较)方法执行所有元素比较,因此,从设置,相等。 集合的行为是明确定义的,即使其排序与等式不一致;只是不遵守 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. (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 element comparisons using its compareTo (or compare) method, so two elements 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.

以下是仅(?)的示例实现 Comparable 但与 equals()

Set<BigDecimal> decimals = new HashSet<BigDecimal>();
decimals.add(new BigDecimal("42"));
decimals.add(new BigDecimal("42.0"));
decimals.add(new BigDecimal("42.00"));
System.out.println(decimals);

十进制最后有三个值,因为 42 42.0 42.00 不尽相同与 equals()有关。但是,如果将 HashSet 替换为 TreeSet ,则结果集中仅包含1个项目( 42 -恰好是第一个添加的),因为使用 BigDecimal.compareTo()

decimals at the end have three values because 42, 42.0 and 42.00 are not equal as far as equals() is concerned. But if you replace HashSet with TreeSet, the resulting set contains only 1 item (42 - that happened to be the first one added) as all of them are considered equal when compared using BigDecimal.compareTo().

这表明当使用与 TreeSet 处于 中断状态$ c> equals()。它仍然可以正常工作,并且所有操作都定义明确-只是不遵守 Set 类的约定-如果两个类的值不等于 equal( ),它们不视为重复项。

This shows that TreeSet is in a way "broken" when using types not consistent with equals(). It still works properly and all operations are well-defined - it just doesn't obey the contract of Set class - if two classes are not equal(), they are not considered duplicates.

  • What does comparison being consistent with equals mean ? What can possibly happen if my class doesn't follow this principle?