Set<E>接口和List<E>接口的根本区别是什么?
当前回答
这可能不是您想要的答案,但是集合类的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和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。
Set:
不能有重复值 排序取决于实现。默认情况下,它不是有序的 不能通过索引进行访问
列表:
可以有重复的值 默认订购 可以通过索引访问吗
嗨,已经给出了这么多答案,让我指出一些到目前为止没有提到的地方:
大多数的List实现(ArrayList,Vector)实现了RandomAccess接口,这是一个快速访问的标记接口。Set的实现都没有这样做。 List使用一个特殊的迭代器,称为ListIterator,它支持双向迭代。Set使用只支持单向迭代的迭代器 HashSet占用的内存是ArrayList的5.5倍 相同数量的元素。
List和Set都是接口。它们都扩展了Collection接口。set和list之间的重要区别是:
复制对象
List和Set之间的主要区别是List允许重复,而Set不允许重复。
订单
List是一个有序的集合,它维护插入顺序,这意味着在显示列表内容时,它将以它们插入到列表中的相同顺序显示元素。
Set是一个无序的集合,它不维护任何顺序。很少有维护顺序的Set实现,例如LinkedHashSet(它按照插入顺序维护元素)。
空元素
List允许任意数量的空元素。Set最多只能有一个null元素。
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 为什么元组可以包含可变项?
- 在Jar文件中运行类
- 带参数的可运行?
- 不区分大小写的“in”
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?