我正在尝试构建priorityQueue
的比较器,该比较器从Weighter<? super Vlabel>
类和Distancer<? super Vlabel>
返回。
这是代码:
public static <VLabel, ELabel> List<Graph<VLabel, ELabel>.Edge> shortestPath(
Graph<VLabel, ELabel> G,
Graph<VLabel, ELabel>.Vertex V0,
Graph<VLabel, ELabel>.Vertex V1,
Distancer<? super VLabel> h, //heuristic value
Weighter<? super VLabel> vweighter,
Weighting<? super ELabel> eweighter) {
Stack<Graph<VLabel, ELabel>.Vertex> closedSet
= new Stack<Graph<VLabel, ELabel>.Vertex>();
int initial = G.vertexSize();
PriorityQueue<Graph<VLabel, ELabel>.Vertex> fringe
= new PriorityQueue(initial, new Comparator<Graph<VLabel, ELabel>.Vertex>() {
public int compare(Graph<VLabel, ELabel>.Vertex v0, Graph<VLabel, ELabel>.Vertex v1) {
double temp1 = vweighter.weight(v0.getLabel()) + h.dist(v0, V1);
double temp2 = vweighter.weight(v1.getLabel()) + h.dist(v1, V1);
return - (int) temp1.compareTo(temp2);
}
});
}
然而它无效,因为代码抱怨它无法在比较方法中识别vweighter和h。
顺便说一句,我不允许为最短路径设置任何参数作为最终。
答案 0 :(得分:3)
将vweighter
和h
参数设为最终:
shortestPath(Graph<VLabel, ELabel> G,
Graph<VLabel, ELabel>.Vertex V0,
Graph<VLabel, ELabel>.Vertex V1,
final Distancer<? super VLabel> h, //heuristic value
final Weighter<? super VLabel> vweighter,
Weighting<? super ELabel> eweighter) {
编辑:
如果由于某种原因不允许在参数变量上使用最终运算符,则可以重新声明它们:
final Distancer<? super VLabel> myH = h;
final Weighter<? super VLabel> myVweighter = vWeighter;
然后在比较器中使用重新声明的变量。
更新2:
如果你想创建一个实现类似接口的类,并且你想要改变函数,那么你就是这样做的了:
public class WeightComparator implements
Comparator<Graph<VLabel, ELabel>.Vertex> {
private Graph<VLabel, ELabel> G;
private Graph<VLabel, ELabel>.Vertex V0;
private Graph<VLabel, ELabel>.Vertex V1;
private Distancer<? super VLabel> h; //heuristic value
private Weighter<? super VLabel> vweighter;
private Weighting<? super ELabel> eweighter;
public WeightComparator() {
}
@Override
public int compare(Graph<VLabel, ELabel>.Vertex o1, Graph<VLabel, ELabel>.Vertex o2) {
// Your compare statement
}
// Getters and setters for all variables
}
在实例化时,您应该保留引用并根据需要更新变量。