gpt4 book ai didi

Java 功能接口(interface)说明 - 参数传递到 lambda 表达式

转载 作者:行者123 更新时间:2023-11-30 07:49:20 25 4
gpt4 key购买 nike

我有以下代码,我很难理解。我有一个接口(interface)声明如下:

public interface WeightedRelationshipConsumer {
boolean accept(int sourceNodeId, int targetNodeId, long relationId, double weight);
}

然后我有第二个接口(interface),它接受如下声明的 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;
});

这让我很困惑。具体来说,sourcetargetrelIdweight是什么,又是如何解析的?这 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);
}
}

此外,如果有可能有助于理解此类代码的资源,请提供。谢谢。

最佳答案

您的界面似乎是一个函数式界面:

interface WeightedRelationshipConsumer {
boolean accept(int sourceNodeId, int targetNodeId, long relationId, double weight);
}

这些也称为 SAM 类型(单一抽象方法类型),它们是用 lambda 表达式或方法引用实现的候选对象。

lambda 表达式是实现接口(interface)唯一方法的一种方式。

例如

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 下标签

关于Java 功能接口(interface)说明 - 参数传递到 lambda 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48576351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com