对于每个循环问题 [英] For Each Loop Question

查看:28
本文介绍了对于每个循环问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解 for-each 循环时遇到问题.我熟悉 for-each 的典型结构,其中每个元素都有内置的计数器和赋值语句.但是,在下面的代码中,new"关键字意味着什么?它只执行一次吗?

I'm having problems understanding a for-each loop. I am familiar w/ the typical structure of a for-each, where there is built in counter and assignment statement to each element. However, in the code below what does the "new" keyword imply? Does it execute only once?

for(Integer item : new ArrayList<Integer>(myCollection)){
    myCollection.add(first.intValue() + item.intValue());
}

这等价于下面的 for 循环吗?

Is this equivalent to the following for loop?

for(int ctr = 0; ctr < myCollection.size(); ctr++){
    Integer temp = myCollection.get(ctr);
    myCollection.add(first.intValue() + item.intValue());
}

推荐答案

new 关键字暗示它将创建一个新的 ArrayList,就像它在代码中的任何其他地方一样.

The new key word implies that it will create a new ArrayList, as if it where anywhere else in code.

代码与下面基本相同.在 for-each 循环中使用 new 没有什么特别之处.

The code is basically the same as the following. There is nothing special about using new in a for-each loop.

List<Integer> list = new ArrayList<Integer>(myCollection);
for(Integer item : list){
    myCollection.add(first.intValue() + item.intValue());
}

它与您的替代循环不同,因为当您向其中添加内容时 size() 会发生变化.我假设您希望 ctri 相同.相当于

It is not the same as your alternative loop as the size() changes when you add things to it. I assume you intended for ctr and i to be the same. It is equivalent to

for(int i = 0, size = myCollection.size(); i < size; i++){
    myCollection.add(first.intValue() + myCollection.get(i).intValue());
}

我想象的和

for(int i = 0, size = myCollection.size(); i < size; i++)
    myCollection.add(first + myCollection.get(i));

这篇关于对于每个循环问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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