Win a copy of Java 9 Revealed this week in the Features new in Java 9 forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

ArrayList ListIterator ConcurrentModificationException  RSS feed

 
Sergej Smoljanov
Ranch Hand
Posts: 472
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: 11077
173
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?
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!