“final int i”是怎样的?在Java for循环中工作?
问题描述:
我很惊讶地看到以下Java代码片段已编译并运行:
I was surprised to see that the following Java code snippet compiled and ran:
for(final int i : listOfNumbers) {
System.out.println(i);
}
其中listOfNumbers是一个整数数组。
where listOfNumbers is an array of integers.
我认为最终声明只分配了一次。编译器是否创建了一个Integer对象并更改了它引用的内容?
I thought final declarations got assigned only once. Is the compiler creating an Integer object and changing what it references?
答
想象一下,速记看起来很像这样:
Imagine that shorthand looks a lot like this:
for (Iterator<Integer> iter = listOfNumbers.iterator(); iter.hasNext(); )
{
final int i = iter.next();
{
System.out.println(i);
}
}