Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[Java]Queue in while loop, cannot modify the value?

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:

  • I have a queue list in, let say the size is 10, lets say: a,b,c,d ... j
  • Generate a number between 1 and 2. if 1, pull (remove the top element) else if 2 add new element
  • I will stop the loop until I added 3 new elements
like image 977
javaLearner.java Avatar asked Jan 19 '26 01:01

javaLearner.java


1 Answers

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.

like image 175
Jon Skeet Avatar answered Jan 21 '26 14:01

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!