封闭范围中定义的局部变量计数必须是最终的或有效地是最终的 [英] Local variable count defined in an enclosing scope must be final or effectively final

查看:81
本文介绍了封闭范围中定义的局部变量计数必须是最终的或有效地是最终的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Java lambda表达式计算迭代次数,但是会引发编译时错误:

I am trying to count the number of iterations using Java lambda expressions, but it's throwing a compile time error:

Local variable count defined in an enclosing scope must be final or effectively final


public static void main(String[] args) {

  List<String> names = new ArrayList<String>();
  names.add("Ajeet");
  names.add("Negan");
  names.add("Aditya");
  names.add("Steve");

  int count = 0;

  names.stream().forEach(s->
  {
    if(s.length()>6)
        count++;
  });
}

推荐答案

语句 count ++; 正在重新分配变量 count .

The statement count++; is reassigning the variable count.

这在lambda表达式中是不允许的.在lambda中引用的局部变量必须是最终变量(或有效地是最终变量,这意味着它没有显式声明为最终变量,但是如果添加了 final ,则不会中断)

This is not allowed in a lambda expression. A local variable referenced in a lambda must be final (or effectively final, which means that it is not explicitly declared final, but would not break if final were added)

替代方法是使用原子整数:

The alternative is to use an atomic integer:

AtomicInteger count = new AtomicInteger();

names.stream().forEach(s -> {
    if (s.length() > 6)
        count.incrementAndGet();
});

注意 ,仅当需要修改局部变量时,才应使用原子整数.如果所有这些只是为了计算 count 变量,那么EliotFrish答案中的方法要好得多.

Note that using an atomic integer should be used only if you need to modify the local variable. If all this is just for computing the count variable, then the approach in EliotFrish's answer is much better.

这篇关于封闭范围中定义的局部变量计数必须是最终的或有效地是最终的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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