-1

My problem is simple : listeBalles is an ArrayList<Balle> and here is my code :

for (Balle b : listeBalles) {

        b.changeList(listeBalles);        
}

The matter is that the method b.changeList adds a Balle to the ArrayList listeBalles. I think that this is the matter. Here are the exceptions :

Exception in thread "main" java.util.ConcurrentModificationException

at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)

at java.util.AbstractList$Itr.next(AbstractList.java:343)

at Main.main(Main.java:31)

The line pointed is the for (Balle b : listeBalles) { line.

Thank you for your help.

3
  • See stackoverflow.com/questions/13847695/… for the remove case and how this problem is addressed Commented Apr 24, 2014 at 16:03
  • @demongolem add is different than remove I think. E.g. there is no support in the Iterator to add elements. Commented Apr 24, 2014 at 16:09
  • Ok, then I submit stackoverflow.com/questions/993025/… for your consideration Commented Apr 24, 2014 at 16:11

4 Answers 4

1

Yes, you're right. From ArrayList's JavaDoc:

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.

So basically you're not allowed to modify the List during iterating over it. What is your actual question?

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the answer. But I need to do that so I used Puce's code and it worked.
0

As you cannot add elements to an ArrayList you're currently iterating over, make a copy of that list first.

E.g. try:

for (Balle b : new ArrayList(listeBalles)) {
        b.changeList(listeBalles);         
}

Comments

0

The cause is that you are iterating through the List and modifying it at the same time.

Comments

0

You cannot modify the content of a collection or array while you iterate over it in a for-each loop. What are you actually trying to do?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.