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


当前回答

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

其他回答

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

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

主题名称:列表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

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

谢谢。

List Vs Set

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

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

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

这里有一个关于groovy的明确例子。我创建了一个集合和一个列表。 然后我尝试在每个列表中存储20个随机生成的值。生成的值范围为0 ~ 5

s = [] as Set
l = []

max = 5
print "random Numbers :"
20.times{
e = (int)Math.random()*max
s << e
l << e
print "$e, "
}


println "\n"
println "Set : $s "
println "list : $l

结果:

随机数:4,1,4,0,1,2,4,0,0,0,3,4,2,0,4,4,0,4,0,0,1,3,1,3

集合:[4,1,0,2,3]

列表:[4 1 4 0,1,2,4,0,0,3、4、3、2 0 4 0,1,3,1,3)

你可以看到区别在于:

Set不允许重复值。 列表允许重复值。

List Set
Duplicates Yes No
Order Ordered Depends on implementation
Position Access Yes No