I am iterating a list in Java 7 loop and Java 8 forEach
loop. The Java 8 loop wants the variables inside it to not change. For example:
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
}
Can someone explain why? Is it a drawback of Java 8?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…