Java 扩展方法中的返回类型哈希表
我有一个请求方法的接口节点:Java 扩展方法中的返回类型哈希表,java,hashset,extending,Java,Hashset,Extending,我有一个请求方法的接口节点: public HashSet getnexture() NodeVariable实现了Node,它的邻居是NodeFunction类型(它也实现了Node),我编写了以下方法: public HashSet getnexture() (和NodeFunction类中的viceversa) 我发现如果我将节点中方法的签名更改为: public HashSet getnexture() 然后在NodeVariable和NodeFunction中的方法上,我得到了错误:
public HashSet getnexture()代码>
NodeVariable实现了Node,它的邻居是NodeFunction类型(它也实现了Node),我编写了以下方法:
public HashSet getnexture()代码>
(和NodeFunction类中的viceversa)
我发现如果我将节点中方法的签名更改为:
public HashSet getnexture()代码>
然后在NodeVariable和NodeFunction中的方法上,我得到了错误:
factorgraph.NodeFunction中的错误GetNexter()无法在factorgraph中实现GetNexter()。节点返回类型java.util.HashSet与java.util.HashSet NodeFunction.java不兼容
这并不十分清楚
我发现:
及
现在我在中更改了节点方法签名:
public HashSet首先,最好根据其他接口而不是具体实现来定义接口中的方法。我想说的是getneighbor()
方法应该是:
public Set getNeighbour();
由于我们知道它只能返回节点(或节点的子类型),我们不妨这样定义它:
public Set<? extends Node> getNeighbour();
public SetHashSet
和HashSet
不兼容,即使NodeFunction
实现/子类Node
。同样地,List
和List
也不是<代码>整数
子类<代码>数字
static List<Number> getNumberList(int size) {
//ArrayList<Integer> numList = null; //Doesn't compile
ArrayList<Number> numList = null; //Compiles
return numList;
}
除了公共集getneighbor(){}
之外,所有内容在语义/语法上都有效。Java教程涵盖了这个问题。这一点非常清楚。你的链接,也给我完整的解释。非常感谢。好的,你是这么说的
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main( String[] args ) {
Node nd = getInstance();
Set<Node> ndSet = nd.getNeighbour();
ndSet.add( new NodeSign() );
nd.removeSingleNeighbor(); //throws ClassCastException
}
static Node getInstance() {
return new NodeVariable();
}
}
interface Node {
public Set<Node> getNeighbour();
public void removeSingleNeighbor();
}
class NodeVariable implements Node {
Set<NodeFunction> ndFuncList = new HashSet<NodeFunction>();
public Set<NodeFunction> getNeighbour(){ return ndFuncList; } //wont' compile
//HERE!!!!
public void removeSingleNeighbor() {
NodeFunction ndFunc = (NodeFunction)ndFuncList.toArray()[ndFuncList.size()-1]; //throws ClassCastException
}
}
class NodeFunction implements Node {
public Set<NodeFunction> getNeighbour(){ return null; } //won't compile
public void removeSingleNeighbor() {}
}
class NodeSign implements Node {
public Set<NodeFunction> getNeighbour(){ return null; } //won't compile
public void removeSingleNeighbor() {}
}