为什么不应该更改forEach循环内的变量? [英] Why should variables inside a forEach loop not be changed?

查看:106
本文介绍了为什么不应该更改forEach循环内的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遍历Java 7循环和Java 8 forEach循环中的列表. Java 8循环希望其中的变量保持不变.例如:

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
}

有人可以解释为什么吗?这是Java 8的缺点吗?

Can someone explain why? Is it a drawback of Java 8?

推荐答案

Java内存模型具有非常重要的属性:它确保局部变量和方法参数永远不会被其他线程写入.这为多线程编程增加了很多安全性.但是,当您创建lambda(或匿名类)时,没人知道如何使用它.可以将其传递给另一个线程执行(例如,如果使用parallelStream().forEach(...)).是否有可能修改局部变量,否则将侵犯重要属性.不是Java语言开发人员会牺牲的事情.

The Java Memory Model has very important property: it guarantees that local variables and method parameters are never writable by another thread. This adds much safety to multi-threading programming. However when you create a lambda (or an anonymous class), nobody knows how it will be used. It can be passed to another thread for execution (for example, if you use parallelStream().forEach(...)). Were it possible to modify the local variable that important property would be violated. Not the thing the Java language developers would sacrifice.

通常,当您使用lambda时,您尝试以功能方式进行编程.但是在函数式编程中,可变变量被认为是不好的做法:每个变量最好只分配一次.因此,尝试修改局部变量实际上会产生异味.使用各种流减少方法代替forEach来产生良好的功能代码.

Usually when you are using lambdas, you are trying to program in functional way. But in functional programming mutable variables are considered bad practice: it's better to assign every variable only once. So trying to modify the local variable actually smells. Use various stream reduction methods instead of forEach to produce a good functional code.

这篇关于为什么不应该更改forEach循环内的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆