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


当前回答

主题名称:列表VS集

我刚刚介绍了Java中最重要的主题——集合框架。我想和你分享我关于收藏的一点知识。其中最重要的是列表、集合、映射。让我们从List和Set开始。

List与Set的区别:

List is a collection class which extends AbstractList class where as Set is a collection class which extends AbstractSet class but both implements Collection interface. List interface allows duplicate values (elements) whereas Set interface does not allow duplicate values. In case of duplicate elements in Set, it replaces older values. List interface allows NULL values where as Set interface does not allow Null values. In case of using Null values in Set it gives NullPointerException. List interface maintains insertion order. That means the way we add the elements in the List in the same way we obtain it using iterator or for-each style. Whereas Set implementations do not necessarily maintain insertion order. (Although SortedSet does using TreeSet, and LinkedHashSet maintains insertion order). List interface has its own methods defined whereas Set interface does not have its own method so Set uses Collection interface methods only. List interface has one legacy class called Vector whereas Set interface does not have any legacy class Last but not the least... The listIterator() method can only be used to cycle through the elements within List Classes whereas we can use iterator() method to access Set class elements

还有什么要补充的吗?请让我知道。

谢谢。

其他回答

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

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

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

嗨,已经给出了这么多答案,让我指出一些到目前为止没有提到的地方:

大多数的List实现(ArrayList,Vector)实现了RandomAccess接口,这是一个快速访问的标记接口。Set的实现都没有这样做。 List使用一个特殊的迭代器,称为ListIterator,它支持双向迭代。Set使用只支持单向迭代的迭代器 HashSet占用的内存是ArrayList的5.5倍 相同数量的元素。

列表:

允许重复。 有序地将元素分组。(换句话说,有明确的顺序。不需要按升序排序)

Set:

不允许复制。 对元素进行无序分组。(换句话说,没有明确的顺序。它可能是也可能不是按升序排列的)

1.List允许重复值,set不允许重复值

2.List维护您在列表中插入元素的顺序 Set不能维持秩序。 3.List是一个有序的元素序列,而Set是一个无序的元素列表。