(TLDR: Why does the while-loop repeat infinitely, where the for-loop always works?)
I am writing an Android
app, and have a queue of Runnable
s that need to be run, then removed from this queue:
List<Runnable> queue = new ArrayList<Runnable>();
I wanted to do this the most optimal way, and thought of the following algorithm:
synchronized(queue)
{
while(queue.size() > 0)
{
queue.remove(0).run();
}
}
This caused errors, so I had to add this check: if (queue.size() > 0)
before the loop (is that really necessary?). Now, however, this seems to be stuck in an infinite loop. I had to change my loop to this, which works well:
synchronized(queue)
{
for (int i = 0; i < queue.size(); i++)
{
queue.get(i).run();
}
queue.clear();
}
My question is - what is the low-level difference between these loops? Why does the while loop fail?