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不允许重复值。 列表允许重复值。
其他回答
Set不能包含重复的元素,而List可以。List(在Java中)也意味着顺序。
订购…列表有顺序,集合没有。
集合是由不同对象组成的无序组——不允许有重复的对象。它通常使用被插入对象的哈希代码来实现。(特定的实现可能会添加排序,但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 |
这可能不是您想要的答案,但是集合类的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.
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 为什么元组可以包含可变项?
- 在Jar文件中运行类
- 带参数的可运行?
- 不区分大小写的“in”
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?