为什么这个 for-each 循环不起作用? [英] Why doesn't this for-each loop work?

查看:31
本文介绍了为什么这个 for-each 循环不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这段代码中,为什么我的数组没有按照我的意愿初始化?for-each 循环是不是为此而设计的,还是我只是没有正确使用它?

In this code, why isn't my array initialised as I want it to? Is the for-each loop not designed to do that, or am I just not using it correctly?

    int[] array = new int[5];

    //initialise array -> Doesn't work! Array still full of 0's
    for(int i : array)
        i = 24;

推荐答案

for-each 循环不适用于这种情况.您不能使用 for-each 循环来初始化数组.您的代码:

The for-each loop will not work for this case. You cannot use a for-each loop to initialize an array. Your code:

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 将集合或数组中的每个条目依次分配给您提供的变量,然后您可以使用该变量.该变量等同于数组引用.它只是一个变量.

If this were an array of objects, it would still fail. Basically, for-each assigns each entry in the collection or array, in turn, to the variable you provide, which you can then work with. The variable is not equivalent to an array reference. It is just a variable.

For-each 不能用于初始化任何数组或集合,因为它循环遍历数组或集合的当前内容,每次给你一个时间.for-each 中的变量不是数组或集合引用的代理.编译器不会用array[index]"替换你的i"(来自int i").

For-each cannot be used to initialize any array or Collection, because it loops over the current contents of the array or Collection, giving you each value one at a time. The variable in a for-each is not a proxy for an array or Collection reference. The compiler does not replace your "i" (from "int i") with "array[index]".

例如,如果您有一个 Date 数组,然后试试这个,代码:

If you have an array of Date, for example, and try this, the code:

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();
}

正如您所见,它不会初始化数组.您最终会得到一个包含所有空值的数组.

which as you can see will not initialize the array. You will end up with an array containing all nulls.

注意:我把上面的代码编译成一个 .class 文件,然后使用 jad 反编译它.这个过程给了我下面的代码,由 Sun Java 编译器 (1.6) 从上面的代码中生成:

NOTE: I took the code above, compiled it into a .class file, and then used jad to decompile it. This process gives me the following code, generated by the Sun Java compiler (1.6) from the code above:

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;
}

这篇关于为什么这个 for-each 循环不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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