1 class Fruit{} 2 class Apple extends Fruit{} 3 class SubApple extends Apple{} 4 class Orange extends Fruit{} 5 6 class Holder<T>{ 7 private T value; 8 public Holder(){} 9 public Holder(T value){this.value = value;} 10 public T getValue() { 11 return value; 12 } 13 public void setValue(T value) { 14 this.value = value; 15 } 16 public boolean equals (Object obj){ 17 return value.equals(obj); 18 } 19 20 } 21 public class CovarianArrays { 22 23 public static void main(String[] args) { 24 Fruit [] fruitArray = new Apple[10]; 25 fruitArray[0] = new SubApple(); 26 //数组有协变类型,能放入SubApple 27 //编译时正常。运行时错误 ArrayStoreException 数组在运行时检查类型 28 //fruitArray[0] = new Fruit(); 29 //fruitArray[1] = new Orange(); 30 31 //编译时就出错 32 //List<Fruit> fruitList = new ArrayList<Apple>(); 33 34 List<Apple> fruitList = new ArrayList<Apple>(); 35 fruitList.add(new Apple()); 36 //只能是Apple,泛型没有协变类型 37 //fruitList.add(new SubApple()); 38 39 List<? extends Fruit> fruitExtendList = new ArrayList<Apple>(); 40 //连Object都不行,只能是无意义的null 41 //fruitExtendList.add(new Apple()); 42 //fruitExtendList.add(new Object()); 43 fruitExtendList.add(null); 44 45 List<? extends Fruit> fruitAsList = Arrays.asList(new Apple()); 46 Apple a = (Apple) fruitAsList.get(0); 47 //以下两个方法的参数都是Object 48 fruitAsList.contains(new Apple()); 49 int i =fruitAsList.indexOf(new Apple()); 50 System.out.println(i);//-1 不存在 51 52 List<? super Apple> supList = new ArrayList<Apple>(); 53 supList.add(new Apple()); 54 supList.add(new SubApple()); 55 //supList.add(new Fruit()); 56 57 Holder<Apple> holdApple = new Holder<Apple>(new Apple()); 58 Apple a1 = holdApple.getValue(); 59 System.out.println(a1); //com.Array.Apple@10b30a7 60 61 //Holder<Fruit> holdFruit = holdApple; 62 Holder<? extends Fruit> holdFruit = holdApple; 63 Fruit f1 = holdFruit.getValue(); 64 System.out.println(f1); //com.Array.Apple@10b30a7 65 Apple a2 = (Apple) holdFruit.getValue(); 66 System.out.println(a2); 67 Orange o1 = (Orange) holdFruit.getValue(); //运行时出错ClassCastException 68 System.out.println(o1); 69 //不能调用setValue() 70 //holdFruit.setValue(new Orange()); 71 72 73 74 } 75 76 }
参考: