无法使用通配符泛型类型向 Java 集合添加值 [英] Can't add value to the Java collection with wildcard generic type
问题描述
为什么这段代码不能编译(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
是这是扩展 Parent
的某种类型的列表.我们不知道哪种类型 - 它可能是一个 List
、List
或 List
."这使得从 List
API 中获取出的任何项目并从 T
转换为 Parent
是安全的,但是将 in 调用到从 Parent
转换为 T
的 List
API 是不安全的.. 因为该转换可能无效.
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屋!