java - java.util.Set API 中可能存在的错误

标签 java collections javadoc comparator

java.util.Set API 状态:

sets contain no pair of elements e1 and e2 such that e1.equals(e2)

但据我了解TreeSet使用Comparable/Comparator确定 e1 和 e2 是否重复。我错过了什么吗?

最佳答案

如果 compareToequals 一致(应该如此),则 TreeSet 使用 compareTo 还是 并不重要equals 来确定相等性。来自 JavaDoc:

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.

即使 equals 始终返回 false,该程序仍将打印“true”。但该错误实际上是 A 的 compareToequals 不一致,而不是 TreeSet 中的错误。

class A implements Comparable<A> {
    public int compareTo(A a) {
        return 0;
    }

    public boolean equals(Object other) {
        return false;
    }

    public static void main(String[] args) {
        TreeSet<A> set = new TreeSet<A>();
        set.add(new A());
        System.out.println(set.contains(new A()));
    }
}

关于java - java.util.Set API 中可能存在的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13541152/

相关文章:

eclipse - 我可以使用 Eclipse 轻松地将 JavaDoc 添加到包中吗?

java - 我需要标准化位图并将其存储在 TensorImage 中。有什么办法可以做到这一点吗?

java - GraalVM 作为 ARM JRE 的 JIT 编译器

csv - 使用node-csv和meteor-file将CSV导入到集合中

java - ManagedExecutorService 从 1.0 开始?

gradle - 配置在gradle中生成javadoc

java - java中如何删除空行和其余字符

java - 通过套接字发送 10 MB 的缓冲区 - block 还是整个 10MB?

java - 随机错误 - java.lang.IllegalArgumentException : Comparison method violates its general contract

C#泛型列表合并