一、泛型
ArrayList<String> nameList=new ArrayList<String>();
上述语句含义:ArrayList集合的子集只能是String类型的。
public class 泛型 { /** * 泛型 */ public static void main(String[] args) { ArrayList<Person> list=new ArrayList<Person>(); list.add(new Teacher("s001")); } } class Person{ String name; int age; } class Teacher extends Person{ String ID; Teacher(String id){ ID=id; System.out.println(ID); } }
结果:
s001
解析:list里能容纳Person类型的对象,其中Person的子类Teacher也可以被视为Person类所以也能被容纳进去。
二、容器类的基本概念
1.Colletion:Collection是最基本的集合接口,List:“有序” ,Set:"唯一",
2. Map:接口,一组成对的“键值对”对象,允许你使用键来查找值。
2.1 添加一组元素
1.Arrays.asList()方法接受一个数组或者是一个用逗号分隔的元素列表(使用可变参数),并将其转换为一个List对象。
public class Text { public static void main(String[] args) { //Arrays.asList()用法 String[] name={"张三","李四"}; List<String> nameList=Arrays.asList(name); //使用这种方法得到的List对象nameList不能使用add()方法和remove()方法,除非确定Lis对象长度不再改变否则慎用。 System.out.println(nameList.get(0)); List<Integer> intList =new ArrayList<Integer>(Arrays.asList(1,2,3)); //Colletions构造器可以接受另一个Colletion用它来初始化,asList()获得一个List对象,向上转型为Colletion类型并作为ArrayList构造器的参数初始化。 System.out.println(intList.get(1)); intList.add(4); //正常使用add() System.out.println(intList.get(3)); } }
结果:
张三
2
4
解析:List<String> nameList=Arrays.asList(name); 中name可以直接用“"张三","李四"”取代。
2.Colletions.addAll()方法接受一个Colletion对象,以及一个数组或者是一个用逗号分隔的列表,将元素添加到Colletion中。
public class Text { public static void main(String[] args) { List<String> name=new ArrayList<String>(); System.out.println(name.size()); Collections.addAll(name, "李四","王五"); System.out.println(name.size()); } }
解析:addAll()方法将所有指定元素添加到指定 collection 中。
)
原文:http://www.cnblogs.com/shyroke/p/6413128.html