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


当前回答

这可能不是您想要的答案,但是集合类的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.

其他回答

订购…列表有顺序,集合没有。

最大的不同在于基本概念。

从设置和列表界面。集合是数学概念。设置方法扩展集合。但是没有添加新的方法。size()表示基数(more为BitSet。基数,线性计数器,日志日志,HyperLogLog)。addAll()表示联合。retainAll()表示交集。removeAll()表示差异。

However List lack of these concepts. List add a lot of method to support sequence concept which Collection interface not supply. core concept is INDEX. like add(index,element),get(index),search(indexOf()),remove(index) element. List also provide "Collection View" subList. Set do not have view. do not have positional access. List also provide a lot of algorithms in Collections class. sort(List),binarySearch(List),reverse(List),shuffle(List),fill(List). the method params is List interface. duplicate elements are just the result of concepts. not the essential difference.

所以本质的区别在于概念。集合是数学集合的概念。列表是序列的概念。

Set<E>和List<E>都用于存储E类型的元素。区别在于Set是以无序方式存储的,不允许重复值。List用于以有序的方式存储元素,并且允许重复值。

Set元素不能通过索引位置访问,而List元素可以通过索引位置访问。

Set不能包含重复的元素,而List可以。List(在Java中)也意味着顺序。

集合是由不同对象组成的无序组——不允许有重复的对象。它通常使用被插入对象的哈希代码来实现。(特定的实现可能会添加排序,但Set接口本身没有。)

列表是一组有序的对象,其中可能包含重复项。它可以用数组列表、链表等来实现。