为什么java8的foreach循环中的变量应该是final? [英] why variables inside foreach loop of java8 should be final?

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

问题描述

我在Java 7循环和Java 8 forEach 循环中迭代数组列表。 Java 8循环希望循环内的变量是最终的。例如,

I am iterating an array list in Java 7 loop and Java 8 forEach loop. Java 8 loop wants variable inside the loop to be final. 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++; // No Error
    } 

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

Can someone explain why it is so ? 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.

通常当你使用lambdas时,你正试图以功能方式编程。但在函数式编程中,可变变量被认为是不好的做法:最好只为每个变量赋值一次。因此,尝试修改局部变量实际上闻起来很有气味。使用各种流减少方法而不是 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.

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

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