ryan
ryan

Reputation: 1

why am i getting Exception for the following simple code snipped?

I am getting exception when i try to display this linked list after using addFirst() and addLast() methods.

import java.util.List;

import java.util.LinkedList;

import java.util.Iterator;

public class File1 {

    public static void main(String ...args){

        LinkedList<Integer> list = new LinkedList<Integer>();
        list.add(1);
        list.add(20);
        list.add(30);       
        Iterator<Integer> iterator = list.iterator();

        while(iterator.hasNext())
            System.out.print(iterator.next() + " ");

        list.add(1,600);        
        System.out.println(list);       
        list.remove(1);
        System.out.println(list);

        System.out.println("now using linked list specific 2 methods...");

        list.addFirst(901);
        list.addLast(902);

            while(iterator.hasNext())   
            System.out.print(iterator.next()+" ");
             //this line throws Exception:

     } //end of main()
} //end of class

Upvotes: 0

Views: 39

Answers (3)

Andreas
Andreas

Reputation: 159086

Running the code I get a ConcurrentModificationException.

Quoting the javadoc:

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.

The 2nd while loop is using the iterator from the 1st while loop, and the list has been "structurally modified". Even if you didn't get this error, the 2nd loop wouldn't work, because the iterator is already at-end.

Add the following before the 2nd loop: iterator = list.iterator();
Or better yet use a for loop: for (Integer value : list)
Or even better, just print the list like you do after add and remove.

Upvotes: 1

Rafiq
Rafiq

Reputation: 750

You can use below code.

    LinkedList<Integer> list = new LinkedList<Integer>();
    list.add(1);
    list.add(20);
    list.add(30);       
    Iterator<Integer> iterator = list.iterator();

    while(iterator.hasNext())
        System.out.print(iterator.next() + " ");

    list.add(1,600);        
    System.out.println(list);       
    list.remove(1);
    System.out.println(list);

    System.out.println("now using linked list specific 2 methods...");

    list.addFirst(901);
    list.addLast(902);
    Iterator<Integer> iterator1 = list.iterator();
     while(iterator1.hasNext())   
     System.out.print(iterator1.next()+" ");
         //this line throws Exception:

Upvotes: 0

Dinusha
Dinusha

Reputation: 716

Create new iterator before second whike loop and print it. Eg: Iterator iterator1 = list.iterator();

Upvotes: 0

Related Questions