Re: How to loop through a list while inside the loop, the list size
may be decreased?
www wrote:
Hi,
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.
for(int i=0; i < list.size(); i++)
{
if(..) //check
{
list.get(i).remove(i); //this decreases the number of objects
in list, correct?
}
}
Thank you very much.
Try using iterators instead:
for (Iterator<Foo> it = list.iterator(); foo.hasNext();) {
Foo foo = it.next();
if (shouldRemove(foo)) {
it.remove();
}
}
This has the added benefit that you won't accidentally skip the element
after the one you just removed (which is the real bug in your above code).
Hope this helps,
Daniel.
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>