扩展方法中的返回类型哈希表
我有一个 Node 接口,它要求方法:
public HashSet getNeighbour();
NodeVariable 实现 Node,它的邻居是 NodeFunction 类型(也实现 Node),我编写了该方法:
<代码>public HashSet
(在 NodeFunction 类中反之亦然)。
我发现如果我将 Node 中方法的签名更改为:
public HashSet
然后在 NodeVariable 和 NodeFunction 中的方法上出现错误:
factorgraph.NodeFunction中的错误getNeighbour()无法实现factorgraph中的getNeighbour()。Node返回类型java.util.HashSet与java.util.HashSet NodeFunction.java不兼容
这不太清楚。
我发现:
和
Java - 返回时覆盖扩展接口的返回类型type 对自己的方法参数类型使用泛型
,现在我更改了 Node 方法签名:
public HashSet getNeighbour();
因此编译器不再抱怨。
对吗?为什么 HashSet 不被视为 HashSet 的“扩展”?
I have an interface Node that asks for the method:
public HashSet getNeighbour();
NodeVariable implements Node, and its neighbours are of type NodeFunction (that implements Node, too), and I wrote the method:
public HashSet<NodeFunction> getNeighbour();
(and viceversa in NodeFunction class).
I found out that if I change the signature of method in Node to:
public HashSet<Node> getNeighbour();
then on the methods in NodeVariable and NodeFunction I get the error:
Error getNeighbour() in factorgraph.NodeFunction cannot implement getNeighbour() in factorgraph.Node return type java.util.HashSet is not compatible with java.util.HashSet NodeFunction.java
This is not really clear.
I found:
Overriding return type in extended interface - Bad idea?
and
and now I changed the Node method signature in:
public HashSet<? extends Node> getNeighbour();
thus the compiler stops complaining.
Is it right? Why HashSet is not considered like an "extension" of HashSet?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,最好根据其他接口而不是具体实现来定义接口中的方法。我想说的是, getNeighbour() 方法应该是:
而且既然我们知道它只能返回 Node(或 Node 的子类型),我们不妨这样定义它:
First, it's a better idea to define the methods in your interfaces in terms of other interfaces and not concrete implementations. What I want to say is that the
getNeighbour()
method should be:And since we know that it can only return Nodes (or subtypes of Node), we might as well define it like this:
HashSet
和HashSet
不兼容,即使NodeFunction
实现/子类Node
也是如此。同样,List
和List
都不是。Integer
子类Number
。如果编译器允许您尝试执行的操作,那么我可以执行以下操作,并且会抛出 ClassCastException ,这就是创建泛型的确切原因。
除了
public Set之外,所有内容在语义/语法上都是有效的。 getNeighbour(){}
。 Java 教程涵盖了此问题。HashSet<Node>
andHashSet<NodeFunction>
aren't compatible, even thoughNodeFunction
implements/subclassesNode
. Similarly, neither areList<Number>
andList<Integer>
.Integer
subclassesNumber
.If the compiler allowed what your trying to do, then I could do the following and a
ClassCastException
would be thrown, which is the exact reason generics was created.Everything is semantically/syntactically valid except
public Set<NodeFunction> getNeighbour(){}
. The Java tutorials cover this issue.