-1

This is a code snippet to move to next element in the linked list. On debugging, itrPlaylist.next() is triggering a ConcurrentModificationException. I read that the list should not be modified while I am iterating. So, in this case, where did I go wrong? How can it be resolved?

Thanks in Advance.

public boolean nexxt() {
    if(this.itrPlaylist.hasNext())
    {
        if(!bForward)
        {
            bForward = true;
            itrPlaylist.next();
        }
        System.out.println("Now playing : " + itrPlaylist.next());
        return true;    
    }
    else
    {
        System.out.println("Reached end of " + this.getPlaylistName() + " playlist !");
    }
    return false;
}
Jonas
  • 121,568
  • 97
  • 310
  • 388
ashray mp
  • 3
  • 2

1 Answers1

1

Where is itrPlaylist is defined? Somethng like

itrPlaylist = list.iterator();

Above assignment should have happened after all the inserts have been done to the list. Looks like you have created one instance variable for itrPlaylist. And I think you might be doing

list.add(value); 

after itrPlaylist has been initialized.

In that case, code will throw the above mentioned exception. This happens when some other code outside of iterator modifies the list when iterator is already initialized.

aatwork
  • 2,130
  • 4
  • 17
  • Thank You @aatwork. You are right. The mistake was that I initialized the iterator even before I could populate the list. – ashray mp Mar 27 '21 at 07:07