有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java文档中使用的哈希集约定

为什么TreeSetHashSetadd()方法的Oracle Java API文档说明:

an element e is added only if there is no e2 in the set where (e==null ? e2==null : e.equals(e2))

然而,TreeSet使用compareTo(),而HashSet使用hashCode()来确定相等性。两者都忽略equals()的值。我担心文档不准确,或者是我对约定或算法的理解有缺陷


共 (2) 个答案

  1. # 1 楼答案

    您认为TreeSet文档不正确是正确的

    关于HashSet,您是不正确的,因为它使用equals()hashCode()用于相等性测试,仅用于快速搜索

  2. # 2 楼答案

    TreeSet在其文档中解释了这一点:

    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.

    对于HashSet,文档的一个隐含期望是Set中的对象得到正确实现;如果hashCode()没有正确实现,那么它不是HashSet违反了它的规范,而是传递给它的对象