【问题标题】:Exception in thread "main" java.util.ConcurrentModificationException, Not sure why线程“主”java.util.ConcurrentModificationException 中的异常,不知道为什么
【发布时间】:2021-09-30 20:26:58
【问题描述】:

这个“播放列表”类应该能够跳过重播并返回播放列表中的歌曲,该播放列表是歌曲的链接列表,这是另一个类,但是我在线程“main”java.util.ConcurrentModificationException 中收到错误异常 这是我写的播放列表类:(谢谢你)

 package com.sulay;

import java.util.LinkedList;
import java.util.ListIterator;

public class Playlist {

private LinkedList<Song> songs;
private ListIterator<Song> listIterator;
private boolean goingForward = true;

public Playlist() {
    this.songs = new LinkedList<>();
    this.listIterator = this.songs.listIterator();
}

public LinkedList<Song> getSongs() {
    return this.songs;
}

public void addSong(Song song) {
    if(!checkSong(song)) {
        this.songs.add(song);
        System.out.println("Song " + song.getTitle() + " added");
    } else {
        System.out.println("Song " + song.getTitle() + " already exists");
    }
}

public boolean checkSong(Song song) {
    for (Song currentSong : songs) {
        if (currentSong.equals(song)) {
            return true;
        }
    }
    return false;
}

public void skipSong() {
    if (listIterator.hasNext()) {
        
        if (!goingForward) {
            listIterator.next();
            goingForward = true;
        }
        System.out.println(listIterator.next() + " now playing");
    } else {
        System.out.println("No next song");
    }
}

public void previousSong() {
    if (listIterator.hasNext()) {
        
        if (goingForward) {
            listIterator.next();
            goingForward = false;
        }

        System.out.println(listIterator.previous() + " now playing");
    } else {
        System.out.println("No previous song");
    }
}

public void replaySong() {
    if (goingForward){
        goingForward = false;
        System.out.println("Playing " + listIterator.previous());
    } else if (!goingForward) {
        goingForward = true;
        listIterator.next();
        System.out.println("Playing " + listIterator.previous());
    }
}

public void displaySongs() {
    for (Song currentSong : songs) {
        System.out.println("Name: " + currentSong + " Album: " + currentSong.getAlbum());
    }
}

}

【问题讨论】:

标签: java arrays linked-list concurrentmodification


【解决方案1】:

如果允许添加新歌曲,listIterator 的状态不会与列表同步。所以它现在可能会在任何时候抛出ConcurrentModificationException

最好的办法是初始化后不要暴露或使用列表。因此,在您开始播放播放列表后,您无法在其中添加或删除。或者您可以只使用数组列表,即RandomAccess,即它支持恒定时间get 方法和索引变量。这不需要任何列表迭代器。

请记住,您正在通过 getSongs 方法公开可变列表。为了安全起见,将其设为返回值List&lt;Song&gt; 并返回此

return new ArrayList<>(songs);

【讨论】:

    猜你喜欢
    • 2013-05-06
    • 2014-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多