Set<E>接口和List<E>接口的根本区别是什么?


当前回答

Factor List Set
Is ordered grouping elements? YES NO
Provides positional access by index? YES NO
Can store duplicate elements? YES NO
Can store multiple null elements? YES NO
Childs: ArrayList, LinkedList, Vector, and Stack HashSet and LinkedHashSet

其他回答

最大的不同在于基本概念。

从设置和列表界面。集合是数学概念。设置方法扩展集合。但是没有添加新的方法。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是项的有序分组 Set是一个无序的项目分组,不允许重复(通常)

从概念上讲,我们通常将允许重复的无序分组称为Bag,而不允许重复的无序分组称为Set。

列表:

允许重复。 有序地将元素分组。(换句话说,有明确的顺序。不需要按升序排序)

Set:

不允许复制。 对元素进行无序分组。(换句话说,没有明确的顺序。它可能是也可能不是按升序排列的)

列表: 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不允许空值和重复值

订购…列表有顺序,集合没有。