Podo
Podo

Reputation: 709

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.

Upvotes: 2

Views: 8736

Answers (3)

tschwab
tschwab

Reputation: 1096

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++) { ... }

Upvotes: 10

knutesten
knutesten

Reputation: 594

The .size() is called for each iteration. That is why looping over iterators works, if you just evaluated .hasNext() only once the loop would never end. To only iterate over the list the number of times as the original size you could do something like this:

final int originalSize = list.size();

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

Upvotes: 1

Amer Qarabsa
Amer Qarabsa

Reputation: 6574

In the implementation of add() method in ArrayList, a member variable which stores the size of the arraylist is updated and size() represents a getter for this member variable , so on each iteration this size is called so you get the updated version of the size.

Upvotes: 2

Related Questions