To my understanding, lambda expressions capture values, not the variables. For example, the following is a compile-time error:
。for (int k = 0; k < 10; k++) {
new Thread(() -> System.out.println(k)).start();
// Error—cannot capture k
// Local variable k defined in an enclosing scope must be final or effectively final
}
然而,当我尝试使用增强型for循环
运行相同的逻辑时,一切都正常:
List<Integer> listOfInt = new Arrays.asList(1, 2, 3);
for (Integer arg : listOfInt) {
new Thread(() -> System.out.println(arg)).start();
// OK to capture 'arg'
}
为什么增强for循环可以正常工作,而常规的for循环却不能,尽管增强for循环也会像常规循环一样逐步递增变量。