Set<E>接口和List<E>接口的根本区别是什么?
当前回答
Set<E>和List<E>都用于存储E类型的元素。区别在于Set是以无序方式存储的,不允许重复值。List用于以有序的方式存储元素,并且允许重复值。
Set元素不能通过索引位置访问,而List元素可以通过索引位置访问。
其他回答
这可能不是您想要的答案,但是集合类的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.
Set<E>和List<E>都用于存储E类型的元素。区别在于Set是以无序方式存储的,不允许重复值。List用于以有序的方式存储元素,并且允许重复值。
Set元素不能通过索引位置访问,而List元素可以通过索引位置访问。
列表: 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:
不能有重复值 排序取决于实现。默认情况下,它不是有序的 不能通过索引进行访问
列表:
可以有重复的值 默认订购 可以通过索引访问吗
列表:
允许重复。 有序地将元素分组。(换句话说,有明确的顺序。不需要按升序排序)
Set:
不允许复制。 对元素进行无序分组。(换句话说,没有明确的顺序。它可能是也可能不是按升序排列的)
推荐文章
- 你能解释一下流的概念吗?
- 导致java.lang.VerifyError错误的原因
- 如何在Java中监控计算机的CPU、内存和磁盘使用情况?
- 如何设置超时在改造库?
- java lambda可以有一个以上的参数吗?
- HashMap -获取第一个键值
- 使用Jackson将JSON字符串转换为漂亮的打印JSON输出
- Android - SPAN_EXCLUSIVE_EXCLUSIVE跨度不能为零长度
- Javadoc @see或{@link}?
- 在准备语句中使用“like”通配符
- Android Eclipse -无法找到*.apk
- javac和Eclipse编译器之间的区别是什么?
- 工厂模式和策略模式之间的区别是什么?
- 在Java中使用正则表达式提取值
- 如何允许所有网络连接类型HTTP和HTTPS在Android(9)馅饼?