【发布时间】: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());
}
}
}
【问题讨论】:
-
如果在创建
ListIterator之后以任何方式对列表进行了结构修改,除非该修改是通过ListIterator完成的,否则您很可能会得到ConcurrentModificationException。创建迭代器后添加到列表中。 -
欢迎来到 Stack Overflow!请使用tour,环顾四周,并通读help center,尤其是I ask a good question? 和What topics can I ask about here? 是如何做到的。请添加完整的错误消息和Minimal, Complete, and Verifiable example。
标签: java arrays linked-list concurrentmodification