This is my code:
Iterator it = queue.iterator();
while(it.hasNext()){
random = randNumber(1,2);
if(random == 1){
queue.poll();
} else {
queue.add("new");
queue.poll();
}
}
It gives me:
Exception in thread "test" java.util.ConcurrentModificationException
at java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:761)
at java.util.LinkedList$ListItr.next(LinkedList.java:696)
Edit @Jon Skeet:
What I want to do is:
In general, you can't modify collections while you're iterating over them. One alternative is to build a separate list of "changes" you want to apply, and then apply them once you've finished iterating.
Alternatively, some collections do support this such as ConcurrentLinkedQueue - but most offer no guarantees about whether the iterator will see the changes made while you're iterating. (I suspect that's mainly because they're also thread-safe, but I've rarely seen documented guarantees about what will happen if you modify the collection within the iterating thread.)
EDIT: I'm not sure that an iterator is the right approach here. Instead, you could use:
while (!queue.isEmpty())
{
// Put logic in here - add, poll etc
}
One thing to note is that your posted code doesn't actually move the iterator forward at any time - it never calls it.next(). That's a strong suggestion that either you're not using the iterator fully, or you don't need it at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With