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

查看:20
本文介绍了为什么不应该更改 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天全站免登陆