Set<E>接口和List<E>接口的根本区别是什么?
当前回答
最大的不同在于基本概念。
从设置和列表界面。集合是数学概念。设置方法扩展集合。但是没有添加新的方法。size()表示基数(more为BitSet。基数,线性计数器,日志日志,HyperLogLog)。addAll()表示联合。retainAll()表示交集。removeAll()表示差异。
However List lack of these concepts. List add a lot of method to support sequence concept which Collection interface not supply. core concept is INDEX. like add(index,element),get(index),search(indexOf()),remove(index) element. List also provide "Collection View" subList. Set do not have view. do not have positional access. List also provide a lot of algorithms in Collections class. sort(List),binarySearch(List),reverse(List),shuffle(List),fill(List). the method params is List interface. duplicate elements are just the result of concepts. not the essential difference.
所以本质的区别在于概念。集合是数学集合的概念。列表是序列的概念。
其他回答
这里有一个关于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不允许重复值。 列表允许重复值。
Java中List和Set之间的一些值得注意的区别如下:
1) Java中的List和Set之间的基本区别是允许重复元素。Java中的List允许重复,而Set不允许任何重复。如果在Set中插入duplicate,它将替换旧的值。Java中Set的任何实现都只包含唯一的元素。
2) Another significant difference between List and Set in Java is order. List is an Ordered Collection while Set is an unordered Collection. List maintains insertion order of elements, means any element which is inserted before will go on lower index than any element which is inserted after. Set in Java doesn't maintain any order. Though Set provide another alternative called SortedSet which can store Set elements in specific Sorting order defined by Comparable and Comparator methods of Objects stored in Set.
3) Java中比较流行的List接口实现有ArrayList, Vector和LinkedList。而流行的Set接口实现包括HashSet, TreeSet和LinkedHashSet。
很明显,如果你需要维护插入顺序或对象,你的集合可以包含重复的列表是一种方法。另一方面,如果您的要求是保持唯一的集合,没有任何重复,那么Set是最好的方法。
List是项的有序分组 Set是一个无序的项目分组,不允许重复(通常)
从概念上讲,我们通常将允许重复的无序分组称为Bag,而不允许重复的无序分组称为Set。
List | Set | |
---|---|---|
Duplicates | Yes | No |
Order | Ordered | Depends on implementation |
Position Access | Yes | No |
订购…列表有顺序,集合没有。