每个回路问题 [英] For Each Loop Question

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

问题描述

我有问题,理解一个for-each循环。我熟悉瓦特/的的for-each典型的结构,其中有内置的计数器和赋值语句每个元素。然而,在下面的code是什么新的关键字意味着什么呢?它是否只执行一次?

 为(整数项目:新的ArrayList<整数GT;(myCollection)将){
    myCollection.add(first.intValue()+ item.intValue());
}

这是等同于循环以下?

 的for(int CTR = 0;&CTR LT; myCollection.size(); CTR ++){
    整数TEMP = myCollection.get(CTR);
    myCollection.add(first.intValue()+ item.intValue());
}


解决方案

键字意味着它会创建一个新的ArrayList,因为如果它在其他地方code。

的code是基本相同如下。没有什么特别之处在for-each循环利用新的。

 列表<整数GT;名单=新的ArrayList<整数GT;(myCollection)将;
对于(整数项目:名单){
    myCollection.add(first.intValue()+ item.intValue());
}

这是不一样的另类环路的大小()当你添加的东西它的变化。我假设你打算点击率 I 是相同的。它相当于

 的for(int i = 0,大小= myCollection.size(); I<大小;我++){
    myCollection.add(first.intValue()+ myCollection.get(ⅰ).intValue());
}

这是我想象的是一样的。

 的for(int i = 0,大小= myCollection.size(); I<大小;我++)
    myCollection.add(第一+ myCollection.get(I));

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

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

解决方案

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

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

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

which I imagine is the same as

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

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

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