• Post Reply Bookmark Topic Watch Topic
  • New Topic

current modification exception  RSS feed

 
Abigail Decan
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


this gave me


Exception in thread "main" java.util.ConcurrentModificationException
at java.util.LinkedList$ListItr.checkForComodification(Unknown Source)
at java.util.LinkedList$ListItr.next(Unknown Source)
at MyList.getNext(MyList.java:23)
at MyList.main(MyList.java:49)


i don't understand why.

apparently the line

is the problem.
but i'm not modifying my linked list with this code.
 
Daryl Cofer
Greenhorn
Posts: 19
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When your iterator calls the next method, it checks to see if its expectedModCount is equal to the list's modCount it is iterating over. If these numbers don't match, the iterator thinks that the list has been modified and it throws the exception that you received.
 
Stephan van Hulst
Saloon Keeper
Posts: 7969
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To add to what Daryl already said, the reason these numbers don't match, is because you're initializing i with an iterator and you add values to the list before using it.

It's usually a bad idea to keep references to iterators outside of a method scope. The only time I've needed this myself was when I was implementing an iterator that traverses trees depth-first, and kept a reference to a recursive iterator.
 
Daryl Cofer
Greenhorn
Posts: 19
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The LinkedList class already has a built in iterator anyway, so why would you want to make a new one?
If you want to go through the elements in your MyList class, you might want to look into making it iterable by implementing the Iterable interface.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!