在我的代码的开头,有:
List> result = new ArrayList();
然后,(这里是反转一个子列表):
List sub = new ArrayList();
re = reverse(result.get(j)); // error occurs here
有这种方法:
public ArrayList reverse(ArrayList list) {
List newList = new ArrayList<>();
for(int i=list.size()-1; i>=0; i--) {
newList.add(list.get(i));}
return newList;
}
}
错误消息是:
List cannot be converted to ArrayList
为什么?
想象一下,你有一个名为re的Fruit(我使用这个名字,因为它是你正在使用的变量的名称).
Fruit re;
你有一个方法反向,其输入类型是Apple.
public Apple reverse(Apple a) {
// ...
}
我们有一个变量re我们宣称为Fruit,这意味着我们说它总是会成为某种水果,也许是Apple,但也许是Orange – 甚至是香蕉.
当你尝试将Fruit用于采用Apple的方法时,编译器会阻止你,因为它无法确定它是100%的Apple.例如…
Fruit re = new Orange();
reverse(re);
哎呀!我们正在将一个方形钉子放入一个圆孔中,可以这么说.逆转需要苹果,而不是橙色.坏事可能发生!
Side note: Why is it okay then to assign Apple to something declared as Fruit then? (reverse returns an Apple, Fruit f = reverse(re); is legal.) Because an Apple is a Fruit. If it were declared as the more specific Apple and the return type were the more general Fruit, then there would be an issue here. (If reverse returned Fruit, Apple a = reverse(re); would be illegal.)
如果你没有按照这个比喻,用List替换Fruit with List,用ArrayList替换Apple,再读上面的内容.列表是水果,一种描述抽象概念的一般方式. ArrayList是Apple,是抽象概念的具体实现. (LinkedList也可能是Orange.)
通常,您希望将事物声明为获得所需功能的最常用的事物.进行以下更改应该可以解决您的问题.
public List reverse(List list) {
我们正在使用某种整数列表并返回某种整数列表.