java list 改变变量的值,Java-在Lambda中更改最终变量的值

In Java I have the following code

List myList = new ArrayList<>();

for (int i=0;i<9;i++) {

myList.add(i);

}

Integer sum = 0;

myList.forEach(i -> {

sum = sum + i; // does not compile, sum needs to be final or effectively final

});

for(int i : myList) {

sum = sum + i; //runs without problems

}

My question is, why is it exactly that I cannot change the value of sum from within the lambda? It does the exact same thing as the for loop down below, or am I wrong? Interesting is also the fact that if I declare the Integer sum outside of the main method as static, it works as well. Can anyone explain me why?

EDIT: In another similar question Does Java 8 support closures, the answer seems to be :

it is a combination of backwards compatibility and project resourcing constraints.

However I still cannot understand why it works if I make sum an array or if I declare it outside of main. I would also like to understand what is the difference between the myList.forEach and the for loop below, why the one works and the other one doesn't.

解决方案

Try with:

final Integer[] sum = new Integer[1];

sum[0] = 0;

myList.forEach(i -> {

sum[0] = sum[0] + i; // does not compile, sum needs to be final or effectively final

});

Since lambda is actually a syntactic sugar for initializing an anonymous class (and overriding a method).

It's the same as if you have written:

final Integer[] sum = new Integer[1];

sum[0] = 0;

myList.forEach(new Consumer() {

public void accept(Integer element) {

sum[0] = sum[0] + element;

}

});

The variable that comes from outer scope and that you use within inner scope must be final (in this example sum). That is simply because Java does not support closures. Therefore, outer variable must be marked as final. Since Integer itself is immutable (if you declare it final, you cannot change it anymore), you have to use a wrapper object or an array (as I did).

You can find more useful info here:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值