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


当前回答

List Vs Set

1) Set不允许重复。列表允许重复。基于Set的实现,它还维护插入顺序。

LinkedHashSet。它维护插入顺序。请参考此处

2)包含方法。根据集合的性质,它将为访问提供更好的性能。最好的情况是o(1)但是List有调用contains的性能问题。

其他回答

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

从设置和列表界面。集合是数学概念。设置方法扩展集合。但是没有添加新的方法。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.

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

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

当我们讨论Java接口时,为什么不看看Javadoc呢?!

List是一个有序的集合(序列),通常允许 重复的 集合是不包含重复元素的集合,迭代 顺序可以由实现来保证

这里没有提到关于集合的缺乏顺序:这取决于实现。

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

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

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