码迷,mamicode.com
首页 > 其他好文 > 详细

泛型高级之通配符

时间:2020-04-05 13:19:53      阅读:89      评论:0      收藏:0      [点我收藏+]

标签:extend   obj   pre   list   code   super   span   end   lis   

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>();        //错误

 

泛型高级之通配符

标签:extend   obj   pre   list   code   super   span   end   lis   

原文地址:https://www.cnblogs.com/buhuiflydepig/p/12636643.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!