【发布时间】:2014-10-10 15:59:07
【问题描述】:
我想知道Java 不能将ArrayList<ArrayList<T>> 隐式转换为Iterable<Iterable<T>> 的原因。
我的问题不在于如何明确地做到这一点。
为什么会出现以下代码:
import java.util.Iterator;
import java.util.ArrayList;
public class Test {
public Test() {
ArrayList<ArrayList<Test>> arr = new ArrayList();
Iterable<Iterable<Test>> casted = arr;
}
}
在编译期间引发以下错误?
Test.java:7: error: incompatible types: ArrayList<ArrayList<Test>> cannot be converted to Iterable<Iterable<Test>>
【问题讨论】:
-
因为你可以做
casted.add(new LinkedList());,或者添加任何其他实现Iterable的东西,即使casted应该只包含ArrayList<Test>的对象。 -
不,我不能这样做
arr.add(new LinkedList());因为 arr 仍然是ArrayList<ArrayList<Test>>。我也做不到casted.add(new LinkedList());,因为 Iterable 没有实现 add。 -
好的,是的。但是如果你改为
List<List<Test>>会发生什么?那有一个add方法。对于Iterable的情况,语义上没有问题(因为Iterables 是只读的),但对于一般情况,它允许您违反内部模板的类型,因此Java 不允许您这样做。 -
到目前为止,这些答案已经提到了如何解决这个问题,但他们没有解释为什么需要解决这个问题。
标签: java generics bounded-wildcard