为什么这段代码不编译(Parent
是一个接口(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)
最佳答案
这样做是为了安全起见。想象一下它是否有效:
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>
的含义是“这是扩展 Parent
的某种类型的列表。我们不知道是哪种类型 - 它可能是 List<Parent>
、List<Child>
或 List<GrandChild>
。”这使得从 List<T>
中提取任何项目 变得安全API 并从 T
转换至 Parent
, 但是调用 in 到 List<T>
是不安全的API 从 Parent
转换而来至 T
...因为该转换可能无效。
关于java - 无法使用通配符泛型向 Java 集合添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28833112/