List和Set这两个接口都属于Collection框架。这两个接口都扩展了Collection接口。它们都用于将对象集合存储为单个单元。
在jdk1.2之前,我们曾经使用Arrays,Vectors和Hashtable将对象分组为一个单元。
| 序号 | 键 | 列表 | 组 |
|---|---|---|---|
| 1个 | 位置访问 | The list provides positional access of the elements in the collection. | Set不提供对集合中元素的位置访问 |
| 2 | 实作 | Implementation of List are ArrayList,LinkedList,Vector ,Stack | 设置接口的实现是HashSet和LinkedHashSet |
| 3 | 重复 | We can store the duplicate elements in the list. | 我们不能在Set中存储重复的元素 |
| 4 | 定购 | List maintains insertion order of elements in the collection | 集不维护任何顺序 |
| 5 | 空元素 | The list can store multiple null elements | 集只能存储一个空元素 |
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
public class ListExample {
public static void main(String[] args) {
List<String> al = new ArrayList<String>();
al.add("BMW");
al.add("Audi");
al.add("BMW");
System.out.println("List Elements: ");
System.out.print(al);
}
}输出结果
List Elements: [BMW, Audi, BMW]
import java.util.Set;
import java.util.HashSet;
import java.util.TreeSet;
public class SetExample {
public static void main(String args[]) {
int count[] = {2, 4, 3, 5};
Set<Integer> hset = new HashSet<Integer>();
try{
for(int i = 0; i<4; i++){
hset.add(count[i]);
}
System.out.println(hset);
}
catch(Exception e){
e.printStackTrace();
}
}
}输出结果
[2, 4, 3, 5]