泛型高级之通配符
Posted buhuiflydepig
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了泛型高级之通配符相关的知识,希望对你有一定的参考价值。
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>(); //错误
以上是关于泛型高级之通配符的主要内容,如果未能解决你的问题,请参考以下文章