gpt4 book ai didi

java - 当我将 lambda 表达式作为参数传递时,它怎么可能访问此范围内的其他变量?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:07:08 25 4
gpt4 key购买 nike

public class ArraysDemo {

public static void main(String[] args) {

int[] a = {0, 2, 4, 6, 8};
int[] b = {10, 12, 14, 16, 18};
Arrays.setAll(a, i -> b[i]+1);
System.out.println(Arrays.toString(a));
}
}

输出:[11, 13, 15, 17, 19]

使用到的setAll()函数的源码如下:

public static void setAll(int[] array, IntUnaryOperator generator) {
Objects.requireNonNull(generator);
for (int i = 0; i < array.length; i++)
array[i] = generator.applyAsInt(i);
}

IntUnaryOperator 是一个函数式接口(interface),这是其源代码的一部分:

public interface IntUnaryOperator {
int applyAsInt(int operand);
// rest methods are omitted
}

如果我错了请纠正我,但我对 Java 中的 lambda 表达式的理解是,当我将 lambda 表达式作为参数传递给 setAll() 方法时,匿名类的对象实现 IntUnaryOperator 接口(interface)被创建并被称为 generator。而 lambda 表达式本质上是 applyAsInt() 方法的一个实现,所以我相信它会转化为如下内容:

int applyAsInt(int operand){
return b[operand]+1;
}

它可以访问 operand 对我来说很有意义,因为它作为参数传递给 array[i] = generator.applyAsInt(i); 但是,我不明白它如何操作 b - 它不是作为参数传递的,所以它怎么可能被引用?我错过了什么?

最佳答案

原因是 b有效的最终

Instance and static variables may be used and changed without restriction in the body of a lambda. The use of local variables, however, is more restricted: capture of local variables is not allowed unless they are effectively final, a concept introduced in Java 8. Informally, a local variable is effectively final if its initial value is never changed (including within the body of a lambda expression)—in other words, declaring it final would not cause a compilation failure. The concept of effective finality does not introduce any new semantics to Java; it is simply a slightly less verbose way of defining final variables.

来自 http://www.lambdafaq.org/can-lambda-expressions-use-variables-from-their-environment/

关于java - 当我将 lambda 表达式作为参数传递时,它怎么可能访问此范围内的其他变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39204201/

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