• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

iterator leads to error

 
budsy remo
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

This leads to an Exception . ConcurrentModificationException
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15219
36
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The API documentation of ConcurrentModificationException explains why: it is not allowed to change the content of a collection while you are iterating over it. That's what you are doing in the commented out line 18. You can only change the collection you're iterating over by calling methods in the iterator, such as the add method that you are calling in line 19.

See the documentation of ConcurrentModificationException and ListIterator.
 
budsy remo
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am sorry but i commented the wrong line . It was line 18 instead of 19 . And could you tell me that how exactly i make it ok ? Because when i use it1.add() , no elements are added to the collection .
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15219
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You cannot modify a collection, for example by adding elements to it inside the loop, while you are iterating over that collection in a loop.

When you do that and the iterator finds out that you changed the collection without telling him, the iterator will get angry and it will throw a ConcurrentModificationException at you!

The only way to change the collection inside the look is by doing it through methods that are in the iterator (not directly on the collection itself) so that the iterator knows about it.

If you call it1.add(x); then a new element is added to the collection.
 
budsy remo
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried it but it's not getting added to the collection .
 
budsy remo
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When i add the it1.hasNext() line then it results to false .
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15219
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is, but you're not printing the content of the collection after adding the elements. The iterator will be pointing to the element after the one that you just added.

Try removing lines 22 and 23 and replacing them with:

 
budsy remo
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@ Jasper Thanks man . That solved the problem .
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic