泛型高级通配符
【代码实现】
1 package com.hxl; 2 3 public class Animal {} 4 5 class Dog extends Animal {} 6 7 class Cat extends Animal {}
1 package com.hxl; 2 3 import java.util.ArrayList; 4 import java.util.Collection; 5 6 public class Test { 7 8 public static void main(String[] args) { 9 // 这里不报错的条件是,后者类型参数满足前者类型参数要求!! 10 // Collection类型参数若明确写,则必须与ArrayList类型参数保持一致 11 // 可以偷个懒,写?替代ArrayList类型参数 12 Collection<Animal> c1 = new ArrayList<Animal>(); 13 Collection<?> c2 = new ArrayList<Cat>(); 14 Collection<?> c3 = new ArrayList<Dog>(); 15 16 // ? extends E,表示E本身及它的所有子类 17 // Collection<? extends Animal> c4 = new ArrayList<Object>(); 报错是因为Object不是Animal的子类! 18 Collection<? extends Animal> c5 = new ArrayList<Animal>(); 19 Collection<? extends Animal> c6 = new ArrayList<Dog>(); 20 21 // ? super E,表示E本身及它的所有层次的父类 22 Collection<? super Dog> c7 = new ArrayList<Object>(); 23 Collection<? super Dog> c8 = new ArrayList<Animal>(); 24 Collection<? super Dog> c9 = new ArrayList<Dog>(); 25 //Collection<? super Dog> c9 = new ArrayList<Cat>(); 报错是因为Cat不是Dog的父类! 26 } 27 }