【发布时间】:2015-08-04 05:28:56
【问题描述】:
我在 Java 7 循环和 Java 8 forEach 循环中迭代一个列表。 Java 8 循环希望其中的变量不改变。例如:
List<String> testList = Arrays.asList( "apple", "banana", "cat", "dog" );
int count = 0;
testList.forEach(test -> {
count++; // Compilation error: Local variable count defined in an enclosing scope must be final or effectively final
});
for (String test : testList) {
count++; // Code runs fine
}
有人能解释为什么吗?这是 Java 8 的缺点吗?
【问题讨论】: