我遇到了 java 抽象类和泛型函数的问题。该实现是 Dijkstra 算法图中的节点类。
public abstract class Node {
float distance;
Node parent;
public void relax(Node parent, Edge edge, PriorityQueue<? extends Node> priorityQueue) {
if (this.distance > parent.distance + edge.weight){
this.distance = parent.distance + edge.weight;
this.parent = parent;
priorityQueue.remove(this);
priorityQueue.add(this);
}
}
}
问题出在这一行:
priorityQueue.add(this);
因为 this 引用了 Node 类(它是抽象的),所以它不能被添加到优先级队列中,实际上应该是 ? 类型(节点的子类),在 ? 中表示。扩展节点。如何引用这个子类类型?
提前致谢。
最佳答案
我不确定你想达到什么目的。我看到两种变体。您可以使用节点的一种类型的子类,然后可以编写如下内容:
public <T extends Node> void relax(T parent, Edge edge, PriorityQueue<T> priorityQueue) {
if (this.distance > parent.distance + edge.weight){
this.distance = parent.distance + edge.weight;
this.parent = parent;
priorityQueue.remove(this);
priorityQueue.add((T) this);
}
}
或者您只想使用不同类型的节点并混合和匹配它们,但队列的类型将只是 PriorityQueue<Node>
.
关于Java抽象类泛型方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37071719/