java.util.Set
API 状态:
sets contain no pair of elements e1 and e2 such that e1.equals(e2)
但据我了解TreeSet
使用Comparable/Comparator
确定 e1 和 e2 是否重复。我错过了什么吗?
最佳答案
如果 compareTo
与 equals
一致(应该如此),则 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 的 compareTo
和 equals
不一致,而不是 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/