Java泛型上下界
有如下类的继承关系
// ok
Fruit apple = new Apple();
List<Fruit> plate = new ArrayList<Apple>();
它会在Idea里报红线,运行会报错:java: 不兼容的类型: java.util.ArrayList<Apple>无法转换为java.util.List<Fruit>
,显然在集合间不存在继承引用关系
泛型的上界, ? extends T
使用泛型的上界,? extends Fruit
,就能解决如上问题
List<? extends Fruit> plate = new ArrayList<Apple>();
?只能取,不能存
【只能取】
List<Apple> appleList = new ArrayList<>();
appleList.add(new Apple());
appleList.add(new Apple());
List<? extends Fruit> plate = appleList;
Fruit fruit = plate.get(0);
【不能存】
使用
List<? extends Fruit> plate = Arrays.asList(new Apple(), new Banana());
Fruit apple = plate.get(0);
Fruit banana = plate.get(1);
在这种情况下,这个plate真的成了能装任何水果的盘子
,里边有Apple和Banana,取出来之后确实都是Fruit。
泛型的下界, ? super T
能存
// 定义了一个plate,它的下界为 ? super Apple
List<? super Apple> plate = new ArrayList<>();
plate.add(new Apple());
plate.add(new RedApple());
plate.add(new GreenApple());
也能取
不过取出来的东西都是Object
,使其中元素的类型失效了,而且因为? super Apple
这个范围太大了,不知道拿出来是具体什么类型,只能用最高的Object来进行引用了
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!