I need to execute/display a series of events from a Arraylist to a JTextArea, however, each Event gets execute with different time. Following is the code, it fails while at second Event in the loop:
Thread worker = new Thread(new Runnable()
{
public void run()
{
while (eventList.size() > 0)
for (Event ev : eventList)
if(ev.ready())
{
/*try
{
Thread.sleep(1000);
} catch (InterruptedException e1)
{
e1.printStackTrace();
}*/
jTextArea.append(ev.toString() + "\n");
eventList.remove(ev);
}
}
});
worker.start();
I guess you got a
ConcurrentModificationException. Try using an iterator, something like this:Edit
Why did it throw a ConcurrentModificationException?
If you loop over a collection, using an
Iteratordirectly or by usingfor(E : list), and you modify the collection, by callingadd,removeor similar, you will get this exception. This tries to indicate there is a problem in the code. The problem is, one piece of code wants to loop over all the objects, while another piece of code adds or removes objects. The first piece of code gets in to trouble, how can it loop over everything if the collection keeps changing? So ‘they’ decided, you are not allowed to change a collection, when you loop over it. (Unless you change it with the iterator you use to loop, as this code does.it.remove(),itis the looping iterator and thus does not fail.) Hope that makes sense.