简体   繁体   English

使用java foreach语句时出错

[英]Error occured while using java foreach statements

My code as follows 我的代码如下

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

I run the program and I found its output is 5 15 . 我运行程序,我发现它的输出是5 15 It made me confused,I can't understand what differences between using for statements and using foreach statements.Thanks for giving me a hand. 这让我感到困惑,我无法理解使用for语句和使用foreach语句之间的区别。谢谢你帮助我。

Changes to the iteration variable in an enhanced-for statement do not affect the underlying collection. 对enhanced-for语句中的迭代变量的更改不会影响基础集合。 So while this modifies the array: 所以虽然这会修改数组:

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

... this doesn't: ......这不是:

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

Because the array isn't modified, the next time you iterate over it, the values are still null, so you'll increment your counter another 5 times. 因为数组未被修改,所以下次迭代它时,值仍为空,因此您将计数器再增加5次。 Ditto the third time you iterate over the array. 第三次遍历数组时也是如此。

The moral of the story is: don't use an enhanced for loop if you want to modify the content of the collection/array. 故事的寓意是:如果要修改集合/数组的内容,请不要使用增强的for循环。

Note that changes to the objects whose references are already stored in the collection/array doesn't count as modifying the collection/array. 请注意,对其引用已存储在集合/数组中的对象的更改不计入修改集合/数组。 So if you'd already populated the collection and had some setName() method, then this: 所以如果你已经填充了集合并且有一些setName()方法,那么这个:

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

would be equivalent to: 相当于:

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

That's not changing the array, which just contains references to objects - instead, it's changing the data within those objects. 这并没有改变数组,它只包含对象的引用 - 相反,它正在改变这些对象中的数据。

You can't modify the underlying data structure using the extended for-loop ("foreach"), your test = new Test(); 您无法使用扩展的for循环(“foreach”)修改基础数据结构, test = new Test(); doesn't change the array. 不会更改数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Java中执行javascript代码时发生错误 - error occured while executing the javascript code in java 加载Java VM时出现Windows错误2 - Windows error 2 occured while loading the Java VM 使用 Java Spark foreach 函数迭代数据帧时出错 - Error while iterating a dataframe using Java Spark foreach function java.lang.RuntimeException:执行doInBackground()时发生错误 - java.lang.RuntimeException:An error occured while executing doInBackground() java.lang.RuntimeException:执行doInBackground()URI时发生错误 - java.lang.RuntimeException: An error occured while executing doInBackground() URI 在MS-Access中插入日期时,java中发生错误 - While inserting a date in MS-Access an Error Occured in java 致命异常:AsyncTask#1 java.lang.RuntimeException:在执行doInBackground()并将图像发送到服务器时发生错误 - FATAL EXCEPTION: AsyncTask #1 java.lang.RuntimeException: An error occured while executing doInBackground(), while sending an image to the Server java - 在java中使用mysql创建连接和执行SQL查询语句时出错或代码类型错误 - Error or wrong type of code while creating connection & execute SQL query statements using mysql in java 使用NEO4J-JDBC-Driver的Java EE应用程序中的多条语句出错 - Error while Multiple Statements in a Java EE application using NEO4J-JDBC-Driver 如何解决错误java.lang.RuntimeException:执行doInBackground()时发生错误? - how to solve the error java.lang.RuntimeException: An error occured while executing doInBackground()?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM