permaculture playing cards*
The moose likes Java in General and the fly likes iterator leads to error Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "iterator leads to error" Watch "iterator leads to error" New topic
Author

iterator leads to error

budsy remo
Ranch Hand

Joined: Sep 20, 2008
Posts: 103

This leads to an Exception . ConcurrentModificationException
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14114
    
  16

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
budsy remo
Ranch Hand

Joined: Sep 20, 2008
Posts: 103
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

Joined: Aug 16, 2005
Posts: 14114
    
  16

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

Joined: Sep 20, 2008
Posts: 103
I tried it but it's not getting added to the collection .
budsy remo
Ranch Hand

Joined: Sep 20, 2008
Posts: 103
When i add the it1.hasNext() line then it results to false .
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14114
    
  16

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

Joined: Sep 20, 2008
Posts: 103
@ Jasper Thanks man . That solved the problem .
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: iterator leads to error