Java泛型找不到符号混淆



我目前被作业难住了。我在Generics工作,遇到了一个错误,我不明白为什么会出现这个错误。任何帮助都将不胜感激!

错误如下:

C:path>javac *.java
Graph.java:76: error: cannot find symbol
String nodeLabel = node.getLabel();
^
symbol:   method getLabel()
location: variable node of type N
where N is a type-variable:
N extends Object declared in class Graph

我在下面的代码中,在发生此错误的行旁边放了一条注释

以下是相关方法:

public void propogate(N node, float lambda, Graph<N,L> otherGraph) {
//find degree of node
int theDegree = getDegreeOfNode(node);
//determine num of susceptible neighnbors to be infected
int numToInfect = -1;
for (int i = 0; i < theDegree + 1; i++) {
float calc = (newInfected + i) / infectNodesProc;
if (compare(calc, lambda) > 0) {
float val1 = calc - lambda;
float val2 = lambda - ((newInfected + (i - 1)) / infectNodesProc);
if (compare(val1, val2) < 0) {
numToInfect = i;
} else {
numToInfect = i - 1;
}
break;
}
}
if (numToInfect > 0) {
otherGraph.infectNeighbors(node, theDegree, numToInfect);

newInfected += numToInfect;
}

infectNodesProc++;
}
public void infectNeighbors(N node, int theDegree, int numToInfect) {
//get equivalent node in this graph
String nodeLabel = node.getLabel(); // THIS IS THE LINE THAT THE ERROR IS TALKING ABOUT
Iterator<N> it = nodes.iterator();
N theNode = null;
while (it.hasNext()) {
N aNode = it.next();
if (aNode.getLabel().equals(nodeLabel)) {
theNode = aNode;
break;
}
}
ArrayList<N> suscNeighbors = getSuscNeighbors(theNode);
int toInfect = numToInfect;
while (suscNeighbors.size() > 0 && toInfect > 0) {
Random rand = new Random();
int randInd = rand.nextInt(suscNeighbors.size());
N removedNode = suscNeighbors.remove(randInd);
removedNode.state = StateEnum.INFECTIOUS;
toInfect--;
}
}

上面的两个方法在Graph<N、 L>班

Node类是当String nodeLabel=Node.getLabel((行时Generic的N参数;被调用。这个类存在,所以我知道在我的包或任何东西中找到这个类都不是问题。此外,getLabel((方法是公共的,可以访问,所以它不是不正确的访问修饰符等问题。我很确定它与Generics有关。我必须做<N扩展节点>或者Graph类顶部的类似内容?

非常感谢!

在代码中,N扩展了Object类(请参阅错误(,当没有为泛型定义显式超类时,就会发生这种情况。这意味着它只能访问该类的函数和变量。据我所知,Object类没有定义一个名为getLabel()的方法,因此您可能应该将类型参数限制为之类的参数

public class Graph<N extends ClassWithLabel, L> {
...
}

最新更新