for-each 循环不适用于这种情况。不能使用 for-each 循环来初始化数组。你的代码:
int[] array = new int[5];
for (int i : array) {
i = 24;
}
将翻译为如下内容:
int[] array = new int[5];
for (int j = 0; j < array.length; j++) {
int i = array[j];
i = 24;
}
如果这是一个对象数组,它仍然会失败。基本上,for-each 依次将集合或数组中的每个条目分配给您提供的变量,然后您可以使用该变量。变量是not相当于数组引用。它只是一个变量。
For-each不能用于初始化any数组或集合,因为它循环遍历数组或集合的当前内容,为您提供每个value一次一个。 for-each 中的变量是not数组或集合引用的代理。编译器不会替换你的“i
“ (从 ”int i
“) 和 ”array[index]
".
例如,如果您有一个日期数组,请尝试以下代码:
Date[] array = new Date[5];
for (Date d : array) {
d = new Date();
}
会被翻译成这样:
Date[] array = new Date[5];
for (int i = 0; i < array.length; i++) {
Date d = array[i];
d = new Date();
}
如您所见,这不会初始化数组。您最终将得到一个包含所有空值的数组。
注意:我将上面的代码编译成.class
文件,然后使用jad来反编译它。此过程给出了以下代码,由 Sun Java 编译器 (1.6) 根据上面的代码生成:
int array[] = new int[5];
int ai[];
int k = (ai = array).length;
for(int j = 0; j < k; j++)
{
int i = ai[j];
i = 5;
}