user2494741
user2494741

Reputation:

Iterator has an issue in working with next function

I have written the code below but I can't understand why it gives java.util.ConcurrentModificationException.

Can any one please help me?

static LinkedList<Integer> l1 = new LinkedList<Integer>(); 
public static void main(String[] args) 
{
    Scanner ob= new Scanner(System.in);
            Iterator<Integer> l2=l1.iterator();
    ListIterator<Integer> l3=l1.listIterator();
    
    while(true)
    {
                    System.out.println("Enter number (press 0 to exit the loop: ");
        int number=ob.nextInt();
        if(number == 0)
        {
            System.out.println("****");
            break;
        }
        l3.add(number);
    }
            while(l2.hasNext())
                System.out.println(l2.next());
            
}

Upvotes: 0

Views: 61

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075249

You're getting the mod exception because you're modifying the list after getting the iterator but before calling a method on the iterator. You're getting the iterator, then adding to the list (e.g., modifying it), then trying to use the iterator.

Two things:

  1. Put your

    Iterator<Integer> l2=l1.iterator();
    

    line after the input loop.

  2. Use l1.add, not l3.add, and do away with l3 entirely. There's no reason (in this code) to use a ListIterator just to add to the list.

Upvotes: 2

Related Questions