Java Set的唯一对象标识

Jas*_*son 2 java collections set

在Java中,Set不能包含两个唯一的对象,因为List没有该限制。集合中用于标识唯一对象的机制是什么?最有可能是equals方法或hashCode方法的实现,或正在添加的两个对象的实现。有谁知道识别唯一对象的实际机制是什么?是equals方法,hashcode方法还是这两种方法或其他方法?

Lui*_*oza 5

这取决于Set实现方式。对于HashSetLinkedHashSet,它同时使用equalshashCode方法。为此TreeSet,它使用Comparator对象的自然或提供的特定对象Comparator

基本上,Setjavadoc对此进行了解释(强调我的意思):

不包含重复元素的集合。更正式地说,集合不包含元素对e1和e2,使得e1.equals(e2)最多包含一个null元素。顾名思义,此接口对数学集合抽象进行建模。

除了从Collection接口继承的规定外,Set接口对所有构造函数的协定以及add,equals和hashCode方法的协定附加了其他规定

TreeSet因为它实现了,所以它还有另一个行为SortedSet(此接口扩展了该Set接口)。从其javadoc(重点是我的):

一个Set,进一步提供其元素的总体排序。元素使用其自然顺序或通过通常在排序集创建时提供的Comparator进行排序。集合的迭代器将以升序顺序遍历集合。)

Note that the ordering maintained by a sorted set (whether or not an explicit comparator is provided) must be consistent with equals if the sorted set is to correctly implement the Set interface (See the Comparable interface or Comparator interface 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 sorted set performs all element comparisons using its compareTo (or compare) method.