Set<E>接口和List<E>接口的根本区别是什么?
当前回答
Set不能包含重复的元素,而List可以。List(在Java中)也意味着顺序。
其他回答
列表:
列表通常允许重复对象。 列表必须是有序的,因此可以通过索引访问。
实现类包括:ArrayList, LinkedList, Vector
Set:
集合不允许重复对象。 大多数实现是无序的,但它是特定于实现的。
实现类包括: HashSet(无序) LinkedHashSet(命令), 树集(按自然顺序或按提供的比较器排序)
列表: List允许重复元素和空值。易于搜索使用相应的索引的元素,也将显示元素在插入顺序。 例如:(linkedlist)
import java.util.*;
public class ListExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Integer> l=new LinkedList<Integer>();
l.add(001);
l.add(555);
l.add(333);
l.add(888);
l.add(555);
l.add(null);
l.add(null);
Iterator<Integer> il=l.iterator();
System.out.println(l.get(0));
while(il.hasNext()){
System.out.println(il.next());
}
for(Integer str : l){
System.out.println("Value:"+str);
}
}
}
输出:
1 1 555 333 888 555 零 零 值:1 值:555 值:333 值:888 值:555 值:空 值:空
设置: Set不允许任何重复元素,它允许单个空值。它不会维护显示元素的任何顺序。只有TreeSet将按升序显示。
例如:(TreeSet)
import java.util.TreeSet;
public class SetExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeSet<String> set = new TreeSet<String>();
try {
set.add("hello");
set.add("world");
set.add("welcome");
set.add("all");
for (String num : set) {
System.out.println( num);
}
set.add(null);
} catch (NullPointerException e) {
System.out.println(e);
System.out.println("Set doesn't allow null value and duplicate value");
}
}
}
输出:
所有 你好 欢迎 世界 java.lang.NullPointerException Set不允许空值和重复值
订购…列表有顺序,集合没有。
设置: Set的集合中不能有Duplicate元素。它也是一个无序集合。要从Set中访问数据,只需要使用Iterator,基于索引的检索是不可能的。它主要用于需要唯一性收集的时候。
列表: List可以有重复的元素,插入时使用自然顺序。 因此,它可以基于索引或迭代器检索数据。它广泛用于存储需要基于索引进行访问的集合。
最大的不同在于基本概念。
从设置和列表界面。集合是数学概念。设置方法扩展集合。但是没有添加新的方法。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.
所以本质的区别在于概念。集合是数学集合的概念。列表是序列的概念。
推荐文章
- 从枚举中选择一个随机值?
- 如何从URL获取参数与JSP
- 如何在Eclipse中生成Javadoc注释?
- 检查字符串是否包含字符串列表中的元素
- 找到java类从哪里加载
- 从集合中随机选取一个元素
- 为什么x == (x = y)和(x = y) == x不一样?
- 什么Java 8流。收集等价物可在标准Kotlin库?
- 等待未来的名单
- 如何检查JSON键是否存在?
- 为什么MongoDB Java驱动在条件中使用随机数生成器?
- 即使从未抛出异常,使用try-catch块的代价是否昂贵?
- 什么时候我们应该使用观察者和可观察对象?
- Java中的split()方法对点(.)不起作用。
- 如何有效地比较两个无序列表(不是集合)?