java list 转arraylist_Java List无法转换为ArrayList

在我的代码的开头,有:

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) {

我们正在使用某种整数列表并返回某种整数列表.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值