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

标签 java interface arraylist

我有一个接口(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/

相关文章:

java - wsdl 没有服务元素

Java Instanceof 方法混淆

java - 需要传递给我的方法的 'this' 的解释

java - 为什么我不能在迭代器上调用特定的类方法?

Java:数组在类之间传输,但值却不能?

java - 从 LDAP groupOfUniqueNames 中提取多值属性

java - 如何使自定义 ListView 在单击列表项时打开其他 Activity ?

java - jms 客户端应用程序所需的最少 Jas 数量

c# - 接口(interface)实例化与类实例化

java - Collection.removeIf 工作很奇怪