gpt4 book ai didi

Java : explain Closure in this code

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:50:26 25 4
gpt4 key购买 nike

我了解闭包,并在某些语言(例如 Python 和 SML)中应用过。然而,当我阅读有关 Java 闭包的维基百科时(当然,只有 8 个版本),我不明白 Java 在他们的示例中是否支持闭包的区别。

我从维基百科复制的那些代码:Closure

没有闭包的java代码:

class CalculationWindow extends JFrame {
private volatile int result;
...
public void calculateInSeparateThread(final URI uri) {
// The expression "new Runnable() { ... }" is an anonymous class implementing the 'Runnable' interface.
new Thread(
new Runnable() {
void run() {
// It can read final local variables:
calculate(uri);
// It can access private fields of the enclosing class:
result = result + 10;
}
}
).start();
}
}

如果 Java 支持闭包,代码将如下所示:

class CalculationWindow extends JFrame {
private volatile int result;
...
public void calculateInSeparateThread(final URI uri) {
// the code () -> { /* code */ } is a closure
new Thread(() -> {
calculate(uri);
result = result + 10;
}).start();
}
}

所以,我的问题是:如果 Java 支持闭包,那么第二个代码中有什么特别之处?我真的看不出两个代码之间的主要区别。

请告诉我这一点。

谢谢 :)

最佳答案

重点是它们在功能上并没有太大的不同:

() -> {
calculate(uri);
result = result + 10;
}

等效于 Runnable 的新类实例,具有 run() 方法的等效实现。您用一个简单的 lambda 函数替换了大量“样板”代码。

使用 lambda,您的代码将变得更具表现力、更简洁、更易于编写且可读性更强。一旦您进入闭包和 lambda 函数的世界,这就是好处的开始。

关于Java : explain Closure in this code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14784577/

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