Re: How to loop through a list while inside the loop, the list size may be decreased?

www wrote:

I have a List containing Person objects. I am going through the list using a for loop. Inside the loop, I check each Person obj, if he/she disqualifies, I want to delete the object from the list.

I found that the for loop always run into out of index exception, because the list size is gradually decreased, but the for loop "remembers" the original size.
In your code below the for-loop gets the current list size in each iteration. Hence it does not remember the original size.
Therefore I think the index exception has another cause.

for(int i=0; i < list.size(); i++)
if(..) //check
list.get(i).remove(i); //this decreases the number of objects //in list, correct?
The above line is plain wrong in my eyes, because remove(int) is used on the wrong object (see the API doc of java.util.List). Correct would be



Thank you very much.