我有一个接口(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):
- java generics covariance
- Java covariance
- Java collections covariance problem
- Using generic collections in arguments
解决方案:
更改有问题的方法的返回类型。即改变
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/