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


当前回答

这里有一个关于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是一个无序的元素列表(谢谢你,Quinn Taylor)。

(<和>:

有序集合(也称为 序列)。本界面的用户 有精确的控制在哪里 列出插入的每个元素。的 用户可以通过它们来访问元素 整数索引(在列表中的位置), 并搜索列表中的元素。

Set <和>:

不包含 重复的元素。更正式, 集合不包含元素e1对 e2使得e1。等于(e2) at 最多一个空元素。正如所暗示的 的名称,此接口模拟 数学集合抽象。

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接口本身没有。)

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

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

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

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