实现和集合
为什么这不起作用...
public ArrayList<Edge> getEdges() {
return A;
//A is an Arraylist of type 'Action'. Action implements Edge.
}
Edge 接口包括: public ArrayList getEdges();
尽管如此。
public Edge getEdges() {
return B;
//B is an 'Action'. Action implements Edge.
}
Edge 接口包括: public Edge getEdges();
谢谢你, 切特
Why does this not work...
public ArrayList<Edge> getEdges() {
return A;
//A is an Arraylist of type 'Action'. Action implements Edge.
}
the interface Edge includes: public ArrayList getEdges();
even though this does.
public Edge getEdges() {
return B;
//B is an 'Action'. Action implements Edge.
}
the interface Edge includes: public Edge getEdges();
Thank You,
Chet
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为虽然
Edge
是Action
的子类型,但ArrayList
不是ArrayList
的子类型。使用 ArrayList。
您可以查看本教程的 4. 通配符部分,尽管我建议您阅读它,因为它确实很有帮助。
Because while
Edge
is a subtype ofAction
,ArrayList<Action>
is not a subtype ofArrayList<Edge>
.Use
ArrayList<? extends Edge>
instead.You could take a look at this tutorial's 4. Wildcard section, although I'd suggest to just read through it, because it is really helpful.
这是因为
ArrayList
不是协变 类型为E
。也就是说,您不能仅仅因为Derived
继承自Base
而用ArrayList
实例替换ArrayList
代码>.考虑这种情况:
String
继承自Object
; 但是,如果这意味着您可以使用ArrayList
作为ArrayList
:无法工作,因为您无法将
Integer
添加到ArrayList
。如果可以的话,那么这可能会发生:正如 Ziyao 指出的,正确的方法实现这个是用
吗?扩展 Edge
语法。This is because
ArrayList<E>
is not covariant on the typeE
. That is, you cannot substitute an instance ofArrayList<Derived>
forArrayList<Base>
just becauseDerived
inherits fromBase
.Consider this case:
String
inherits fromObject
; however, if this meant you could use anArrayList<String>
as anArrayList<Object>
then the following code would be possible:The above can't work, because you can't add an
Integer
to anArrayList<String>
. If you could, then this could happen:As Ziyao has indicated, the correct way to implement this is to use the
? extends Edge
syntax.香蕉是一种水果。香蕉列表不是水果列表。
否则,有人可以构建一个香蕉列表,向您传递对水果列表的引用,然后您(正确地)在其中插入一个苹果。香蕉清单的所有者一定会感到惊讶。
A banana is a fruit. A list of bananas is not a list of fruit.
Oherwise someone could construct a list of bananas, pass you a reference to a list of fruit, and you'd (correctly) insert an apple in it. The owner of the list of the bananas would be rightfully surprised.
因为泛型类型必须始终相同,而不是从它扩展的类型,因此您可以像这样重写以使其正常工作:
Because the generic type must always be the same, not something that extends from it you can rewrite like this for it to work: