3

I wrote a simple code for LinkedList, to add data into it and iterate over it,
I imported the required packages for LinkedList and Iterator, There is no error in the Code,

I am getting the following Exception -

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.LinkedList$ListItr.checkForComodification(Unknown Source)
    at java.util.LinkedList$ListItr.next(Unknown Source)
    at collectionFramework.Demo.displayList(LinkedListDemo.java:38)
    at collectionFramework.LinkedListDemo.main(LinkedListDemo.java:13)

Here's my code -

package collectionFramework;

import java.util.Iterator;
import java.util.LinkedList;

public class LinkedListDemo{

    public static void main(String[] args) {

        Demo obj = new Demo();

        obj.addToList();
        obj.displayList();
    }

}

class Demo{

    LinkedList<String> al;
    Iterator<String> itr;  

    Demo(){
        al = new LinkedList<String>();
        itr = al.iterator();
    }

    void addToList(){
          al.add("Aniruddha");  
          al.add("Hitesh");  
          al.add("Rahul");  
          al.add("Kshitij");  
    }

    void displayList(){

        while(itr.hasNext()){  
               System.out.println(itr.next());  
        }
    }
}
Dev1ce
  • 5,390
  • 17
  • 90
  • 150

3 Answers3

5

You should get iterator in your display method, like:

void displayList(){
    itr = al.iterator();
    while(itr.hasNext()){  
           System.out.println(itr.next());  
    }
}

For the LinkedList has a field modCount, this field is used to record the number of times this list has been strucutred modified.

The number of times this list has been structurally modified. Structural modifications are those that change the size of the list, or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.

When you first create the iterator, the modCount is 0, for the ListItr has recorded the expectedModCount=modCount=0, after your modification the list. the modCount has been updated, for your example is 4.

when iterator, it will compare the iterator's expectedModCount and List modCount, if not equal, the ConcurrentModifyExpection throw.

chengpohi
  • 14,064
  • 1
  • 24
  • 42
  • Because ... after the creation of the interator in the constructor, addList is called, changing (concurrently) the list, and on the first usage of the iterator in displayList it detects the concurrent change. – Joop Eggen Aug 17 '16 at 06:45
  • Correct, good catch. The iterator was created too early, then items were added to the collection thereby invalidating the iterator. Exception thrown when you went to use the no-longer-valid iterator. – Basil Bourque Aug 17 '16 at 06:46
2

You cannot add or remove an element from the list once you obtain the iterator from the list. Following code should work.

void displayList(){
    Iterator<String> itr = al.iterator();
    while(itr.hasNext()){  
           System.out.println(itr.next());  
    }
}

For further reading refer the following link:

Iterating through a Collection, avoiding ConcurrentModificationException when removing in loop

http://javahungry.blogspot.com/2014/04/fail-fast-iterator-vs-fail-safe-iterator-difference-with-example-in-java.html

Community
  • 1
  • 1
AmanSinghal
  • 2,404
  • 21
  • 22
2

First you get

 itr = al.iterator();

Then you add some elements to list

al.add("Aniruddha");  
al.add("Hitesh");  
al.add("Rahul");  
al.add("Kshitij");  

Which makes the iterator obsolete.

You should get new iterator before displaying list

void displayList(){
    itr = al.iterator();
    while(itr.hasNext()){  
           System.out.println(itr.next());  
    }
}

Or add elements via iterator:

itr.add("Aniruddha");  
itr.add("Hitesh");  
...  

But this is not what you want, as hasNext() on itr will return false

mlecz
  • 985
  • 11
  • 19