泛型高级通配符

【代码实现】

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 }

 

转载于:https://www.cnblogs.com/schiller-hu/p/8451816.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值