使用java foreach语句时发生错误

时间:2016-05-10 10:07:46

标签: java

我的代码如下

public class Test {

    public static void main(String[] args) {
        int count1 = 0, count2 = 0;
        Test[] test1 = new Test[5];
        Test[] test2 = new Test[5];
        if (test1 == null || test2 == null)
            System.out.println("null");
        for (int j = 0; j < 3; j++) {
            for (int i = 0; i < test1.length; i++) {
                if (test1[i] == null) {
                    test1[i] = new Test();
                    count1++;
                }
            }
        }
        for (int j = 0; j < 3; j++) {
            for (Test test : test2) {
                if (test == null) {
                    test = new Test();
                    count2++;
                }
            }
        }
        System.out.println(count1 + " " + count2);
    }
}

我运行程序,发现它的输出为5 15。 这让我感到困惑,我无法理解使用for语句和使用foreach语句之间的区别。谢谢你帮助我。

2 个答案:

答案 0 :(得分:11)

对增强型for语句中的迭代变量的更改 not 会影响基础集合。因此,虽然这会修改数组:

test[i] = new Test(); // In for loop

......这不是:

test = new Test(); // In enhanced for loop

因为数组未被修改,所以下次迭代它时,值仍然为null,因此您将计数器再增加5次。第三次迭代数组时也是如此。

故事的寓意是:如果你想修改集合/数组的内容,不要使用增强的for循环。

请注意,对其引用已存储在集合/数组中的对象的更改不计入修改集合/数组。因此,如果您已经填充了该集合并使用了一些setName()方法,那么:

for (int i = 0; i < test1.length; i++) {
    test[i].setName("foo");
}

相当于:

for (Test test : test1) {
    test.setName("foo");
}

这不是改变数组,它只包含对象的引用 - 相反,它正在改变这些对象中的数据。

答案 1 :(得分:3)

您无法使用扩展的for-loop(“foreach”)修改基础数据结构,您的test = new Test();不会更改数组。