Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ArrayList ListIterator ConcurrentModificationException

 
Sergej Smoljanov
Ranch Hand
Posts: 467
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

is this mean that after get ListIterator you cant directly modify ArrayList and after use ListIterator that you get before?
why this not allowed?
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the javadoc of the Arraylist class:
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. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Adding a new element to the list is considered a structurally modification of the list. If you change linemyArrList.add("Four"); to iterator.add("Four"); the code will run without the ConcurrentModificationException being thrown. This results in another question: how many strings will be printed after using the ListIterator's add method? 3 or 4?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic