I was trying to make a playlist belonging to "Song" class having fields-(String) 'title' and (int) 'duration'. It doesn't have any compilation error but throws ConcurrentModificationException whenever I try to operate list.
I've tried to operate on a copy of the list but it didn't work.
I've read that use of for loop throws this error but I'm only using Iterator:
while (!quit) {
int input = s.nextInt();
s.nextLine();
switch (input) {
case 0:
System.out.println("exiting");
quit = true;
break;
case 1:
if (!goingforward) {
if (listIterator.hasNext())
listIterator.next();
goingforward = true;
}
if (listIterator.hasNext())
System.out.println("now playng: " +
listIterator.next().getTitle());
else {
System.out.println("At end of the list");
goingforward = false;
}
break;
case 2:
if (goingforward) {
if (listIterator.hasPrevious())
listIterator.previous();
goingforward = false;
}
if (listIterator.hasNext())
System.out.println("Now playing: " +
listIterator.previous().getTitle());
else {
System.out.println("At top of the list");
goingforward = true;
}
break;
case 3:
if (goingforward)
System.out.println("Now playing: " +
listIterator.previous().getTitle());
else
System.out.println("Now playing: " +
listIterator.next().getTitle());
break;
default:
System.out.println("invalid");
}
Expected: Traverse through a list of songs added to the playlist with output: Now playing Why we live
1(INPUT)
Now playing Save Me
Output:
Now playing Why we live
1.Skip to forward
2.Skip to Previous
3.replay
- quit
1(INPUT)
Exception in thread "main" java.util.ConcurrentModificationException at java.base/java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:970) at java.base/java.util.LinkedList$ListItr.next(LinkedList.java:892) at Mian.main(Mian.java:49)
A
LinkedListis not thread safe. I suggest using a data structure that is thread likeVector.Note that using thread safe data structures will impact performance.
Other than
Vectorwhich is a legacy class you can find many data structures in thejava.util.concurrentpackage, see what suits your needs. You can find them here.