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

泛型高级通配符

时间:2018-02-17 13:09:36      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:ros   str   pos   body   dog   实现   port   util   lis   

【代码实现】

1 package com.hxl;
2 
3 public class Animal {}
4 
5 class Dog extends Animal {}
6 
7 class Cat extends Animal {}
 1 package com.hxl;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collection;
 5 
 6 public class Test {
 7 
 8     public static void main(String[] args) {
 9         // 这里不报错的条件是,后者类型参数满足前者类型参数要求!!
10         // Collection类型参数若明确写,则必须与ArrayList类型参数保持一致
11         // 可以偷个懒,写?替代ArrayList类型参数
12         Collection<Animal> c1 = new ArrayList<Animal>();
13         Collection<?> c2 = new ArrayList<Cat>();
14         Collection<?> c3 = new ArrayList<Dog>();
15 
16         // ? extends E,表示E本身及它的所有子类
17         // Collection<? extends Animal> c4 = new ArrayList<Object>(); 报错是因为Object不是Animal的子类!
18         Collection<? extends Animal> c5 = new ArrayList<Animal>();
19         Collection<? extends Animal> c6 = new ArrayList<Dog>();
20 
21         // ? super E,表示E本身及它的所有层次的父类
22         Collection<? super Dog> c7 = new ArrayList<Object>();
23         Collection<? super Dog> c8 = new ArrayList<Animal>();
24         Collection<? super Dog> c9 = new ArrayList<Dog>();
25         //Collection<? super Dog> c9 = new ArrayList<Cat>(); 报错是因为Cat不是Dog的父类!
26     }
27 }

 

泛型高级通配符

标签:ros   str   pos   body   dog   实现   port   util   lis   

原文地址:https://www.cnblogs.com/schiller-hu/p/8451816.html

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