I have a rather simple question about variable scope.

关于变量范围,我有一个相当简单的问题。

I am familiar with the Enhanced For-Loops but I do not get why I should declare a new variable to keep each element. One example might clarify my question:

我熟悉增强的For-Loops,但我不明白为什么我应该声明一个新变量来保存每个元素。一个例子可能澄清我的问题:

        int[] ar = {1, 2, 3};
        int i = 0;
        for(i : ar) {  // this causes an error if I do not declare a new variable: int i
//        for(int i : ar) // this works fine
            System.out.println(i);
        }

So why I should declare this new variable? After all i is accessible inside the for loop. I did not want to use any previous value of i, just did not want to declare a new variable. (I guessed for other iterable items it might be faster using the same variable).

那么我为什么要声明这个新变量呢?毕竟我可以在for循环中访问。我不想使用任何以前的i值,只是不想声明一个新变量。 (我猜测其他可迭代项目使用相同的变量可能会更快)。

I guess that's how Enhanced For-Loops were built but does not this break the whole scope idea?

我想这就是增强For For-Loop的构建方式,但这不会破坏整个范围的想法吗?

There is a question rising from the above behavior. Whether the compiler uses the same variable for the whole for loop and just updates its value or it creates a new variable for each iteration?

上述行为引发了一个问题。编译器是否对整个for循环使用相同的变量并只更新其值,或者为每次迭代创建一个新变量?

An interesting part is that if I keep both declaration of int i (before and inside the for loop) I even get a compiler error about

一个有趣的部分是,如果我保留int i的声明(在for循环之前和之内),我甚至会得到编译器错误

Duplicate local variable i

重复的局部变量i

which makes (at least for me) things a bit more strange. So I cannot use the previous declared variable i inside the for loop but neither can I declare a new one inside it with the same name.

这使得(至少对我来说)事情有点奇怪。所以我不能在for循环中使用先前声明的变量i,但我也不能在其中声明一个具有相同名称的新变量。

5 个解决方案

#1


4

So why I should declare this new variable?

那么我为什么要声明这个新变量呢?

Because that's the way the syntax is defined.

因为这是定义语法的方式。

After all i is accessible inside the for loop.

毕竟我可以在for循环中访问。

That's semantics. It's irrelevant to syntax.

这是语义。这与语法无关。

I did not want to use any previous value of i, just did not want to declare a new variable. (I guessed for other iterable items it might be faster using the same variable).

我不想使用任何以前的i值,只是不想声明一个新变量。 (我猜测其他可迭代项目使用相同的变量可能会更快)。

Don 't guess about performance. Test and measure. But in this case there's nothing to measure, because any working code is faster than any non-working code.

不要猜测性能。测试和测量。但在这种情况下,没有什么可衡量的,因为任何工作代码都比任何非工作代码更快。

更多相关文章

  1. JAVA-全局变量与局部变量-继承-封装-(是三节哦!今天的有点多)
  2. 小聊天程序,访问文件之间的变量
  3. 不幸的是,在声明按钮时,模拟器中出现了错误
  4. 环境变量在cron中看不到
  5. java中的成员变量和局部变量的区别
  6. 如何在另一个类中使用静态类中的变量?
  7. 【JAVA】用java编写程序时总提示缺少方法主体或声明抽象的原因
  8. JAVA 静态方法和静态变量和final和※静态import※
  9. Linux(Centos7.X ) 配置Java 环境变量

随机推荐

  1. Java中构造、生成XML简明教程
  2. XML和YAML的使用方法
  3. 在java中使用dom4j解析xml(示例代码)
  4. PlayFramework完整实现一个APP(十四)
  5. java解析XML几种方式小结
  6. XML 非法字符(转义字符)
  7. PlayFramework完整实现一个APP(九)
  8. PlayFramework完整实现一个APP(一)
  9. xml编程(一)-xml语法
  10. Java套接字编程(下)(1)