Set<E>接口和List<E>接口的根本区别是什么?


当前回答

Factor List Set
Is ordered grouping elements? YES NO
Provides positional access by index? YES NO
Can store duplicate elements? YES NO
Can store multiple null elements? YES NO
Childs: ArrayList, LinkedList, Vector, and Stack HashSet and LinkedHashSet

其他回答

这可能不是您想要的答案,但是集合类的JavaDoc实际上非常具有描述性。复制/粘贴:

An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list. Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.

所有List类都保持插入的顺序。它们基于性能和其他特性使用不同的实现(例如ArrayList用于特定索引的访问速度,LinkedList用于简单地维护顺序)。因为没有密钥,所以允许复制。

Set类不维护插入顺序。它们可以选择性地施加特定的顺序(如SortedSet),但通常具有基于一些散列函数的实现定义的顺序(如HashSet)。由于set是通过键访问的,因此不允许重复。

List Set
Duplicates Yes No
Order Ordered Depends on implementation
Position Access Yes No

Set:

不能有重复值 排序取决于实现。默认情况下,它不是有序的 不能通过索引进行访问

列表:

可以有重复的值 默认订购 可以通过索引访问吗

列表:

列表通常允许重复对象。 列表必须是有序的,因此可以通过索引访问。

实现类包括:ArrayList, LinkedList, Vector

Set:

集合不允许重复对象。 大多数实现是无序的,但它是特定于实现的。

实现类包括: HashSet(无序) LinkedHashSet(命令), 树集(按自然顺序或按提供的比较器排序)