1.List接口是Collection的子接口实现List接口的容器类中的元素是有顺序的,而且可以重复。
2.List容器中的元素对应一个整数型的序号记载其在容器中的位置,可以根据序号存取容器中的元素。
3.JDK提供的List容器有Arraylist,Linkedlist等。
1.Set接口是Collection的子接口,Set接口没有提供额外的方法,但实现Set接口的容器类中的元素是
没有顺序的,而且不可以重复。
2.Set容器可以与数学中的“集合”的概念相对应。
3.JDK提供的Set容器有HashSet,TreeSet等。
方法举例:
import java.util.*;
public class Test {
public static void main(String[] args){
Set s1=new HashSet();
Set s2=new HashSet();
s1.add("a"); s1.add("b"); s1.add("c");
s2.add("d"); s2.add("a"); s2.add("b");
//Set和List容器类都有Constructor(Collection c)
//构造方法用于初始化容器类
//s1中的内容copy到sn中
Set sn =new HashSet(s1);
//sn和s2的交集
sn.retainAll(s2);
Set su =new HashSet(s1);
//将s2中添加到su中
su.addAll(s2);
System.out.println(sn);
System.out.println(su);
//list方法举例
List l1=new LinkedList();
for(int i=0;i<5;i++){
l1.add("a"+i);
}
System.out.println(l1);
//第三个位置上加一个a100
l1.add(3,"a100");
System.out.println(l1);
//l1.set(6,"a200");
//System.out.println(l1);
//第二个位置上强制转换打印出来
System.out.println((String)l1.get(2)+" ");
//找到a3的位置
System.out.println(l1.indexOf("a3"));
//把第一个的位置上的去掉
l1.remove(1);
System.out.println(l1);
}
}
运行结果图:
[b, a]
[d, b, c, a]
[a0, a1, a2, a3, a4]
[a0, a1, a2, a100, a3, a4]
a2
4
[a0, a2, a100, a3, a4]