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


当前回答

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

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

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

其他回答

List Vs Set

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

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

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

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

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

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

List

是元素的有序分组。 List用于收集重复的元素。 新方法在List中定义 接口。

Set

是元素的无序分组。 Set用于收集没有重复项的元素。 在Set接口中没有定义任何新方法,因此我们只能对Set子类使用Collection接口方法。

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