gpt4 book ai didi

java - 将接口(interface)作为数组列表类型提供时出现编译错误

转载 作者:搜寻专家 更新时间:2023-11-01 04:05:00 25 4
gpt4 key购买 nike

我有一个接口(interface)定义为

interface ListItem {
public String toString();
public String getUUID();
}

还有一个实现该接口(interface)的类 ( BrowseItem)。当我尝试时:

ArrayList<ListItem> = (method returning ArrayList of type BrowseItem)

我收到不兼容的类型错误 ( found ArrayList<BrowseItem>, require ...<ListItem> )

我是不是处理错了?

最佳答案

Java 泛型不是协变的。

参见(among many other questions on SO):


解决方案:

  • 更改有问题的方法的返回类型。即改变

    List<listItem> = (method returning List of type browseItem)
    // to
    List<listItem> = (method returning List of type listItem)
  • 使用通配符协方差(我认为这就是所谓的):

    List<? extends listItem> = (method returning List of type browseItem)

    请注意 you cannot add items to the list if you take this route .


注意 将列表类型声明为 List<T> 通常是一种很好的做法而不是 ArrayList<T> .上面的伪代码反射(reflect)了这一点。

关于java - 将接口(interface)作为数组列表类型提供时出现编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7010913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com