2、在集合中使用泛型

在集合中使用泛型:

1、集合接口或集合类在 jdk5.0 时都修改为带泛型的结构。
2、在实例化集合类时,可以指明具体的泛型类型。
3、指明完以后,在集合类或接口中凡是定义类或接口时,内部结构(比如:方法、构造器、属性等)使用到类的泛型的位置,都指定为实例化的泛型类型。比如:add(E e) -> 实例化以后:add(Integer e)。
4、注意点:泛型的类型必须是类,不能是基本数据类型。需要用到基本数据类型的位置,拿包装类替换。
5、如果实例化时,没有指明泛型的类型。默认类型为 java.lang.Object 类型。
实例1:
@Test
public void test1(){
    ArrayList<Integer> list =  new ArrayList<Integer>();

    list.add(78);
    list.add(87);
    list.add(99);
    list.add(65);
    // 编译时,就会进行类型检查,保证数据的安全
    list.add("Tom"); // 这行代码编译报错

    for(Integer score : list){
        // 避免了强转操作
        int stuScore = score;
        System.out.println(stuScore);
    }
}
实例2:迭代器
@Test
public void test2(){
    ArrayList<Integer> list =  new ArrayList<Integer>();

    list.add(78);
    list.add(87);
    list.add(99);
    list.add(65);

    Iterator<Integer> iterator = list.iterator();
    while(iterator.hasNext()) {
        int stuScore = iterator.next();
        System.out.println(stuScore);
    }
}
实例3:
@Test
public void test3(){
    // Map<String,Integer> map = new HashMap<String,Integer>();
    // jdk7新特性:类型推断
    Map<String,Integer> map = new HashMap<>();

    map.put("Tom", 87);
    map.put("Jerry", 87);
    map.put("Jack", 67);

    // 泛型的嵌套
    Set<Map.Entry<String, Integer>> entry = map.entrySet();
    Iterator<Map.Entry<String, Integer>> iterator = entry.iterator();

    while(iterator.hasNext()) {
        Map.Entry<String, Integer> e = iterator.next();
        String key = e.getKey();
        Integer value = e.getValue();
        System.out.println(key + "----" + value);
    }
}
实例4:
public class Employee implements Comparable {
    private String name;
    private int age;
    private MyDate birthday;

    public Employee(String name, int age, MyDate birthday) {
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }

    // 省略 getter/setter

    // 没有指明泛型时的写法
    // 按 name 排序
    @Override
    public int compareTo(Object o) {
        if(o instanceof Employee) {
            Employee e = (Employee)o;
            return this.name.compareTo(e.name);
        }
        return 0;
    }
}

================================================================================
    
public class Employee implements Comparable<Employee> {
    private String name;
    private int age;
    private MyDate birthday;

    public Employee(String name, int age, MyDate birthday) {
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }

    // 省略 getter/setter

    // 指明泛型时的写法
    @Override
    public int compareTo(Employee o) {
        return this.name.compareTo(o.name);
    }
}    
原文地址:https://www.cnblogs.com/kehuaihan/p/13592425.html