Set<E>接口和List<E>接口的根本区别是什么?
当前回答
List
是元素的有序分组。 List用于收集重复的元素。 新方法在List中定义 接口。
Set
是元素的无序分组。 Set用于收集没有重复项的元素。 在Set接口中没有定义任何新方法,因此我们只能对Set子类使用Collection接口方法。
其他回答
这可能不是您想要的答案,但是集合类的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的名为List的接口 可以通过索引访问吗
实现使用
LinkedList ArrayList
独特元素列表: 遵循Java名为Set的接口 不能通过索引访问
实现使用
HashSet(无序) LinkedHashSet(命令) 树集(按自然顺序或按提供的比较器排序)
接口Set和List都符合Java的名为Collection的接口
集合是由不同对象组成的无序组——不允许有重复的对象。它通常使用被插入对象的哈希代码来实现。(特定的实现可能会添加排序,但Set接口本身没有。)
列表是一组有序的对象,其中可能包含重复项。它可以用数组列表、链表等来实现。
最大的不同在于基本概念。
从设置和列表界面。集合是数学概念。设置方法扩展集合。但是没有添加新的方法。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.
所以本质的区别在于概念。集合是数学集合的概念。列表是序列的概念。
List Vs Set
1) Set不允许重复。列表允许重复。基于Set的实现,它还维护插入顺序。
LinkedHashSet。它维护插入顺序。请参考此处
2)包含方法。根据集合的性质,它将为访问提供更好的性能。最好的情况是o(1)但是List有调用contains的性能问题。
推荐文章
- 如何格式化Joda-Time DateTime仅为mm/dd/yyyy?
- 如何在POM.xml中引用环境变量?
- 如何在android中复制一个文件?
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- 将整数转换为字符串,以逗号表示千
- 接口方法的最终参数-有什么意义?
- Java中的@UniqueConstraint注释
- 如何在清洁模式下运行eclipse ?如果我们这样做会发生什么?
- 获取java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory异常
- Java中的正则表达式命名组
- c#和Java的主要区别是什么?
- 什么是NullPointerException,我如何修复它?
- 在Java中使用“final”修饰符
- 无法在Flutter上找到捆绑的Java版本
- 如何在Kotlin解析JSON ?