一、泛型
- ArrayList<String> nameList=new ArrayList<String>();
上述语句含义:ArrayList 集合的子集只能是 String 类型的。
解析:list 里能容纳 Person 类型的对象,其中 Person 的子类 Teacher 也可以被视为 Person 类所以也能被容纳进去。
- 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
二、容器类的基本概念
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 nameList=Arrays.asList(name); //使用这种方法得到的List对象nameList不能使用add()方法和remove()方法,除非确定Lis对象长度不再改变否则慎用。
- System.out.println(nameList.get(0));
- List intList =new ArrayList(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
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.bubuko.com/infodetail-1949562.html