使用每个循环的“高级"在 Java 中初始化数组 [英] Initializing an array in Java using the 'advanced' for each loop
本文介绍了使用每个循环的“高级"在 Java 中初始化数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使用高级"for 循环在 Java 中初始化数组?
Is it possible to initialise an array in Java using the 'advanced' for loop?
例如
Integer[ ] numbers = new Integer[20];
int counter = 0;
for ( Integer i : numbers )
{
i = counter++;
}
for ( Integer i : numbers )
{
System.out.println(i);
}
这会打印所有空值,这是为什么呢?
This prints all nulls, why is that?
推荐答案
不,因为您不是分配给数组,而是分配给名为 i
的临时变量.阵列没有看到变化.
No, because you aren't assigning to the array, you are assigning to the temporary variable called i
. The array doesn't see the change.
以下显示了使用普通 for
循环的大致等效代码.这应该更容易看出为什么它无法更新数组:
The following shows roughly equivalent code using the normal for
loop. This should make it easier to see why it fails to update the array:
for (int j = 0; j < numbers.length; j++) {
Integer i = arr[j]; // i is null here.
i = counter++; // Assigns to i. Does not assign to the array.
}
这篇关于使用每个循环的“高级"在 Java 中初始化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文