Jeffrey Dilley Jeffrey Dilley - 11 months ago 43
Java Question

For loop: how is changing ArrayList size interpreted?

When a for loop is being controlled by the size of an ArrayList

(...; i < someArrayList.size(); ...)

but each iteration of the loop is adding an element to the list, how does the loop then recognize that the size is changing? I would think that once the code is sent to the compiler, it would see the size once and then do it until it reaches the original size, but that's clearly not the case. As the size increases, so does the amount of times the loop runs. I would think it wouldn't, so clearly I don't understand how the computer reads this. I'm just wondering how the system reads something like this.

Also, is there some way to make a loop only run the amount of times of the original list size (again element added each iteration)? Assuming you don't know the size beforehand so you can't put in some constant number.

Answer Source

At the beginning of each iteration, the middle expression is evaluated. If it is true, the loop continues. If it is false, the loop breaks. So it will re-evaluate the size every iteration.

To make it loop the number of times of the original size of the list, do something like this:

int size = someArrayList.size();
for (i = 0 ; i < size ; i++) { ... }

Or if you want to get fancy:

for (i = 0, size = someArrayList.size() ; i < size ; i++) { ... }