Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For Each Loop Question

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());
}
like image 220
gerky Avatar asked Dec 04 '25 14:12

gerky


2 Answers

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));
like image 153
Peter Lawrey Avatar answered Dec 07 '25 03:12

Peter Lawrey


The first block of code creates a new ArrayList of Integers, copies the contents of myCollection into it, and then iterates over the resulting ArrayList.

The copy is needed since the original myCollection gets modified inside the loop.

The second block of code isn't equivalent to the first since it adds elements to myCollection while iterating over it. Because of this interaction it won't do what you expect and will result in an infinite loop.

like image 42
NPE Avatar answered Dec 07 '25 04:12

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!