首页 > 代码库 > java 16-8 泛型高级之通配符

java 16-8 泛型高级之通配符


  泛型高级(通配符)
      ?:任意类型,如果没有明确,那么就是Object以及任意的Java类了
      ? extends E:向下限定,E及其子类
      ? super E:向上限定,E极其父类

 1 import java.util.ArrayList; 2 import java.util.Collection; 3 public class GenericDemo { 4 public static void main(String[] args) { 5 // 泛型如果明确的写的时候,前后必须一致 6 Collection<Object> c1 = new ArrayList<Object>(); 7 // Collection<Object> c2 = new ArrayList<Animal>(); 8 // Collection<Object> c3 = new ArrayList<Dog>(); 9 // Collection<Object> c4 = new ArrayList<Cat>();10 11 // ?表示任意的类型都是可以的12 Collection<?> c5 = new ArrayList<Object>();13 Collection<?> c6 = new ArrayList<Animal>();14 Collection<?> c7 = new ArrayList<Dog>();15 Collection<?> c8 = new ArrayList<Cat>();16 17 // ? extends E:向下限定,E及其子类18 // Collection<? extends Animal> c9 = new ArrayList<Object>();19 Collection<? extends Animal> c10 = new ArrayList<Animal>();20 Collection<? extends Animal> c11 = new ArrayList<Dog>();21 Collection<? extends Animal> c12 = new ArrayList<Cat>();22 23 // ? super E:向上限定,E极其父类24 Collection<? super Animal> c13 = new ArrayList<Object>();25 Collection<? super Animal> c14 = new ArrayList<Animal>();26 // Collection<? super Animal> c15 = new ArrayList<Dog>();27 // Collection<? super Animal> c16 = new ArrayList<Cat>();28 }29 }30 31 class Animal {32 }33 34 class Dog extends Animal {35 }36 37 class Cat extends Animal {38 }

 

java 16-8 泛型高级之通配符