如何修复操作LinkedList时并发修改异常



我试图制作一个属于"Song">类的播放列表,该类具有字段-(String)标题'和(int)

'持续时间'我试着对清单的副本进行操作,但没有成功。我已经读到使用for循环会抛出这个错误,但我只使用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");
}

预期:遍历添加到播放列表中的歌曲列表并输出:现在播放为什么我们生活

1(输入)

正在播放Save Me

输出:

现在播放为什么我们生活

1.跳过以转发

2.跳到上一个

3.回放

  1. 退出

1(输入)

线程"main"java.util.ConcurrentModificationException中的异常在java.base/java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:970)位于java.base/java.util.LinkedList$ListItr.next(LinkedList.java:892)在Mian.main(Mian.java:49)

LinkedList不是线程安全的。我建议使用线程式Vector的数据结构。

请注意,使用线程安全的数据结构会影响性能。

除了作为遗留类的Vector之外,您还可以在java.util.concurrent包中找到许多数据结构,看看什么适合您的需求。你可以在这里找到它们。

最新更新