无法使用通配符泛型为Java集合添加值 [英] Can't add value to the Java collection with wildcard generic type

查看:213
本文介绍了无法使用通配符泛型为Java集合添加值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这段代码不能编译( Parent 是一个接口)?

Why this code does not compile (Parent is an interface)?

List<? extends Parent> list = ...
Parent p = factory.get();   // returns concrete implementation
list.set(0, p);   // fails here: set(int, ? extends Parent) cannot be applied to (int, Parent)


推荐答案

这是为了安全起见。想象一下它是否有效:

It's doing that for the sake of safety. Imagine if it worked:

List<Child> childList = new ArrayList<Child>();
childList.add(new Child());

List<? extends Parent> parentList = childList;
parentList.set(0, new Parent());

Child child = childList.get(0); // No! It's not a child! Type safety is broken...

List的含义<? extends Parent> 是这是一个扩展父类的某种类型的列表。我们不知道哪种类型 - 它可能是 List< Parent> ,a List< Child> List< GrandChild> 。这使得安全地获取 List< T> API的任何项 out 并从 T to Parent ,但在中调用并不安全 List< T> 将API从父母转换为 T ...,因为该转换可能无效。

The meaning of List<? extends Parent> is "The is a list of some type which extends Parent. We don't know which type - it could be a List<Parent>, a List<Child>, or a List<GrandChild>." That makes it safe to fetch any items out of the List<T> API and convert from T to Parent, but it's not safe to call in to the List<T> API converting from Parent to T... because that conversion may be invalid.

这篇关于无法使用通配符泛型为Java集合添加值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆