我有下面的代码,我很难理解。我有一个接口声明如下:
public interface WeightedRelationshipConsumer {
boolean accept(int sourceNodeId, int targetNodeId, long relationId, double weight);
}然后我有第二个接口,它接受WeightedRelationshipConsumer声明,如下所示:
public interface WeightedRelationshipIterator {
void forEachRelationship(int nodeId, Direction direction, WeightedRelationshipConsumer consumer);
}然后,在Dijkstra算法的一个实现中,我有以下代码:
private void run(int goal, Direction direction) {
// `queue` is a Priority Queue that contains the vertices of the graph
while (!queue.isEmpty()) {
int node = queue.pop();
if (node == goal) {
return;
}
// `visited` is a BitSet.
visited.put(node);
// Gets the weight of the distance current node from a node-distance map.
double costs = this.costs.getOrDefault(node, Double.MAX_VALUE);
graph.forEachRelationship(
node,
direction, (source, target, relId, weight) -> {
updateCosts(source, target, weight + costs);
if (!visited.contains(target)) {
queue.add(target, 0);
}
return true;
});
}
}这是
graph.forEachRelationship(node, direction, (source, target, relId, weight) -> {
updateCosts(source, target, weight + costs);
if (!visited.contains(target)) {
queue.add(target, 0);
}
return true;
});这让我很困惑。具体地说,什么是source、target、relId、weight,以及如何解决它们?这4个变量没有在这个类中的其他任何地方定义。updateCosts()格式如下:
private void updateCosts(int source, int target, double newCosts) {
double oldCosts = costs.getOrDefault(target, Double.MAX_VALUE);
if (newCosts < oldCosts) {
costs.put(target, newCosts);
path.put(target, source);
}
}此外,如果有可能有助于理解这类代码的资源,请提供。谢谢。
发布于 2018-02-02 13:52:49
您的接口看起来是一个功能接口:
interface WeightedRelationshipConsumer {
boolean accept(int sourceNodeId, int targetNodeId, long relationId, double weight);
}这些类型也称为SAM类型(单个抽象方法类型),它们是使用lambda表达式或方法引用实现的候选类型。
lambda表达式是实现接口拥有的唯一方法的一种方式。
例如
WeightedRelationshipConsumer wrc = (source, target, relId, weight) -> true;这是为其accept方法提供实现的一种方式,其中(source, target, relId, weight)对应于该方法的声明参数,true ( lambda表达式的返回值)也对应于accept方法的返回类型。
您的graph.forEachRelationship方法似乎接受WeightedRelationshipConsumer的一个实例作为它的第三个参数,因此,您可以传递一个lambda表达式作为参数。
就像你的问题中的情况:
graph.forEachRelationship(node, direction, (source, target, relId, weight) -> {
updateCosts(source, target, weight + costs);
if (!visited.contains(target)) {
queue.add(target, 0);
}
return true;
});关于明显缺乏对参数的定义,这只是你的一部分的混淆。Lambda表达式支持类型推断,所以我们不需要再次提供参数的类型,毕竟它们已经在lambda表达式实现的方法(即accept)的签名中声明了。
因此,我们之前的lambda可以声明为:
WeightedRelationshipConsumer wrc = (int sourceNodeId, int targetNodeId, long relationId, double weight) -> true但为了使它们更具可读性,通常会省略这些类型。毕竟,编译器可以从accept的方法签名中推断出参数的类型。
因此,lambda括号中的标识符列表实际上是函数的参数声明。
在Stackoverflow中,java-8标签下有大量的参考资料
https://stackoverflow.com/questions/48576351
复制相似问题