1 package cn.itcast_07; 2 3 import java.util.ArrayList; 4 import java.util.Collection; 5 6 /* 7 * 泛型高级(通配符) 8 * ?:任意类型,如果没有明确,那么就是Object以及任意的Java类了 9 * ? extends E:向下限定,E及其子类 10 * ? super E:向上限定,E极其父类 11 */ 12 public class GenericDemo { 13 public static void main(String[] args) { 14 // 泛型如果明确的写的时候,前后必须一致 15 Collection<Object> c1 = new ArrayList<Object>(); 16 // Collection<Object> c2 = new ArrayList<Animal>(); 17 // Collection<Object> c3 = new ArrayList<Dog>(); 18 // Collection<Object> c4 = new ArrayList<Cat>(); 19 20 // ?表示任意的类型都是可以的 21 Collection<?> c5 = new ArrayList<Object>(); 22 Collection<?> c6 = new ArrayList<Animal>(); 23 Collection<?> c7 = new ArrayList<Dog>(); 24 Collection<?> c8 = new ArrayList<Cat>(); 25 26 // ? extends E:向下限定,E及其子类 27 // Collection<? extends Animal> c9 = new ArrayList<Object>(); 28 Collection<? extends Animal> c10 = new ArrayList<Animal>(); 29 Collection<? extends Animal> c11 = new ArrayList<Dog>(); 30 Collection<? extends Animal> c12 = new ArrayList<Cat>(); 31 32 // ? super E:向上限定,E极其父类 33 Collection<? super Animal> c13 = new ArrayList<Object>(); 34 Collection<? super Animal> c14 = new ArrayList<Animal>(); 35 // Collection<? super Animal> c15 = new ArrayList<Dog>(); 36 // Collection<? super Animal> c16 = new ArrayList<Cat>(); 37 } 38 } 39 40 class Animal { 41 } 42 43 class Dog extends Animal { 44 } 45 46 class Cat extends Animal { 47 }
时间: 2024-11-09 03:53:08