如何在操作LinkedList时修复ConcurrentModificationException?

时间:2019-02-03 10:18:11

标签: java linked-list listiterator

我正在尝试制作一个属于“歌曲” 类的播放列表,该播放列表具有-(String'title'和(int) “持续时间” 。它没有任何编译错误,但是每当我尝试操作列表时,都会抛出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. 退出

1(输入)

  

线程“主”中的异常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)

1 个答案:

答案 0 :(得分:-1)

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

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

除了Vector(这是一个遗留类)之外,您还可以在java.util.concurrent包中找到许多数据结构,以查看适合您需求的数据结构。您可以找到它们here

相关问题