【发布时间】:2019-02-03 10:18:11
【问题描述】:
我试图制作一个属于 "Song" 类的播放列表,其中包含字段-(String) 'title' 和 (int) 'duration '。它没有任何编译错误,但每当我尝试操作列表时都会抛出ConcurrentModificationException。
我尝试对列表的副本进行操作,但没有成功。
我读过使用 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(输入)
现在播放“救救我”
输出:
现在播放我们为什么活着
1.跳转到转发
2.跳到上一个
3.重播
- 退出
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)
【问题讨论】:
-
请仔细阅读发布minimal reproducible example - 您的代码不完整,而且太长,无法证明您的问题
-
Mian.java:49建议问题出在第 49 行的Mian.java文件中。你能指出来吗? -
无论如何 ConcurrentModificationException 通常在我们修改集合时出现,而不是通过迭代器。所以如果你有类似
iterator = collection.iterator(); while(...){...collection.remove(currentElement);...}的东西,你应该把它改成while(..){...iterator.remove();..}。 -
代码不完整不够imfo
-
该帖子确实不完整,因为没有代码显示您何时在迭代时修改列表,因此得到 ConcurrentModificationException。我会给您留下有关异常的 Oracle 文档,以便您可以更详细地查看它:docs.oracle.com/javase/7/docs/api/java/util/…
标签: java linked-list listiterator