For each cycle

I'm having trouble understanding the for-each loop. I am familiar with the typical structure for each, where each element is embedded in the counter and the assignment operator. However, in the code below, what does the “new” keyword mean? Is it done only once?

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

Is this the equivalent of the next for the loop?

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

The keyword newimplies that it will create a new ArrayList, as if it is somewhere else in the code.

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

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

, , () . , ctr i.

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));
+4

ArrayList Integers, myCollection ArrayList.

, myCollection .

, myCollection, . - , , .

+2

, ( new) , . , , . , , .

for(;;) :

List<Integer> auxList = new ArrayList<Integer>(myCollection);
for(int ctr = 0; ctr < auxList.size(); ctr++){
    myCollection.add(first.intValue() + auxList.get(ctr));
}

, :

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

, , foreach .

, !

0

?

.

?

. ,

  • (first,intValue(), ctr, myCollection.get(i), temp item undefined),
  • myCollection, , ,
  • (size() ), ,
  • OutOfMemoryError.

, ,

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

for

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

( )

for (Iterator<Integer> iterator = new ArrayList<Integer>(myCollection).iterator();
     it.hasNext(); ) {
    Integer item = iterator.next();
    myCollection.add(first.intValue() + item.intValue());
}

myCollection ( myCollection - List), ( )

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

... but you are changing myCollectioninside the loop, so this second loop will never reach the end (assuming there is at least one element in it).

This way your ArrayList helps keep your loop well.

0
source

All Articles