为什么增强for循环中的最终变量不是最终的? [英] Why final variable in enhanced for loop does not act final?

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

问题描述

public class EnhancedForTest {
  public static void main(String... args) {
    String[] strArr = {"A", "B", "C", "D"};

    for (final String s : strArr) {
      System.out.println(s);
    }
  }
}







因为String s是最终的delcared,这段代码不应该编译。但是,这工作正常。为什么?



我尝试了什么:



我什么都没有可以尝试!




Since the String s is delcared as final, this code should not compile. However, this is working fine. Why?

What I have tried:

there was nothing i could try !

推荐答案

因为变量 s 的本地循环,因此在每次迭代时重新创建。
Because the variable s is local to the for loop, so it is recreated at each iteration.


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

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