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


当前回答

Set:

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

列表:

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

其他回答

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

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

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

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

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

List是项的有序分组 Set是一个无序的项目分组,不允许重复(通常)

从概念上讲,我们通常将允许重复的无序分组称为Bag,而不允许重复的无序分组称为Set。

元素的有序列表(是否唯一) 遵循Java的名为List的接口 可以通过索引访问吗

实现使用

LinkedList ArrayList

独特元素列表: 遵循Java名为Set的接口 不能通过索引访问

实现使用

HashSet(无序) LinkedHashSet(命令) 树集(按自然顺序或按提供的比较器排序)

接口Set和List都符合Java的名为Collection的接口