泛型高级之通配符
class Animal { } class Dog extends Animal { } class Cat extends Animal { }
//泛型如果明确的写的时候,前后必须一致 Colletion<Object> c1 = new ArrayList<Object>(); Colletion<Object> c2 = new ArrayList<Animal>(); //错误 Colletion<Object> c3 = new ArrayList<Dog>(); //错误 Colletion<Object> c4 = new ArrayList<Cat>(); //错误
1、 ?:表示任意类型
Colletion<?> c5 = new ArrayList<Object>(); Colletion<?> c6 = new ArrayList<Animal>(); Colletion<?> c7 = new ArrayList<Dog>(); Colletion<?> c8 = new ArrayList<Cat>();
2、 ?extends E:向下限定,E及其子类
Colletion<? extends Animal> c5 = new ArrayList<Object>(); //错误 Colletion<? extends Animal> c6 = new ArrayList<Animal>(); Colletion<? extends Animal> c7 = new ArrayList<Dog>(); Colletion<? extends Animal> c8 = new ArrayList<Cat>();
3、 ?super E:向上限定,E及其父类
Colletion<? super Animal> c5 = new ArrayList<Object>(); Colletion<? super Animal> c6 = new ArrayList<Animal>(); Colletion<? super Animal> c7 = new ArrayList<Dog>(); //错误 Colletion<? super Animal> c8 = new ArrayList<Cat>(); //错误