-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.

Andrei Nicusan
  • 4,555
  • 1
  • 23
  • 36
Danvdb
  • 103
  • 2
  • 13
  • See http://stackoverflow.com/questions/13847695/java-delete-arraylist-iterator for the remove case and how this problem is addressed – demongolem Apr 24 '14 at 16:03
  • @demongolem add is different than remove I think. E.g. there is no support in the Iterator to add elements. – Puce Apr 24 '14 at 16:09
  • Ok, then I submit http://stackoverflow.com/questions/993025/java-adding-elements-to-a-collection-during-iteration for your consideration – demongolem Apr 24 '14 at 16:11

4 Answers4

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?

DarkAjax
  • 15,955
  • 11
  • 53
  • 65
Ray
  • 3,084
  • 2
  • 19
  • 27
0

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

blazy
  • 338
  • 1
  • 8
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?

Andrei Nicusan
  • 4,555
  • 1
  • 23
  • 36
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);         
}
Puce
  • 37,247
  • 13
  • 80
  • 152