修改局部变量forEach会产生编译错误:
正常
    int ordinal = 0;
    for (Example s : list) {
        s.setOrdinal(ordinal);
        ordinal++;
    }
随着Lambda
    int ordinal = 0;
    list.forEach(s -> {
        s.setOrdinal(ordinal);
        ordinal++;
    });
知道如何解决这个问题吗?
在lambda中,局部变量需要是final,但实例变量不需要.为什么这样?
在Java 8之前,我们无法在本地类中使用非final变量.但是现在他们允许最终以及有效的决赛(谁的价值观没有改变),可以由当地的班级推荐.我所知道的(如果我错了,请纠正我),他们不支持引用非最终值,因为可以更改值.那么,他们现在如何支持它以及之前为什么不支持它.
我正在研究Java 8流,我唯一的问题是了解lambda,这是为什么对于instance(和static)变量,lambdas中有效的最终警告会被忽略的原因。我似乎无法在网上找到任何提及它,因为大多数网页将刚才讲的是“有效决赛”的定义。
public class LambdaTest {
    int instanceCounter = 0;
    public void method() {
        int localCounter = 0;
        instanceCounter = 5; //Re-assign instance counter so it is no longer effectively final
        Stream.of(1,2,3).forEach(elem -> instanceCounter++); //WHY DOES THE COMPILER NOT COMPLAIN HERE
        Stream.of(1,2,3).forEach(elem -> localCounter++); //Does not compile because localCounter is not effectively final
    }
}
我刚看到这个问题,显然很明显Java应该拒绝访问lambda表达式体内的非final变量.为什么?
编辑:例如,我不明白为什么以下代码有害:
String[] numbers = new String[10]; // put some numerical strings in
BigInteger sum = new BigInteger("0");
numbers.forEach(n -> sum = sum.add(new BigInteger(n)));