Java实现Playlist播放列表类时抛出ConcurrentModificationException异常求助
报错原因
Java集合框架的快速失败(fail-fast)机制规定:迭代器创建后,若直接通过集合对象修改了集合的结构(增删元素等操作),后续再使用该迭代器时就会抛出ConcurrentModificationException。
你的代码在构造方法中提前初始化了全局的listIterator,后续调用addSong方法时直接调用songs.add()修改了LinkedList的结构,导致全局迭代器失效,调用播放相关方法时就触发了异常。
修复方案
推荐用播放索引替代全局迭代器的方案,从根源避免迭代器失效问题,修改成本更低:
1. 调整成员变量
移除原有全局listIterator和goingForward变量,改为记录当前播放索引:
private LinkedList<Song> songs; // 记录当前播放的索引,-1代表无歌曲正在播放 private int currentIndex = -1;
2. 重写播放相关方法
// 跳过下一首 public void skipSong() { if (currentIndex + 1 < songs.size()) { currentIndex++; System.out.println(songs.get(currentIndex) + " now playing"); } else { System.out.println("No next song"); } } // 返回上一首 public void previousSong() { if (currentIndex - 1 >= 0) { currentIndex--; System.out.println(songs.get(currentIndex) + " now playing"); } else { System.out.println("No previous song"); } } // 重播当前歌曲 public void replaySong() { if (currentIndex >= 0 && currentIndex < songs.size()) { System.out.println("Playing " + songs.get(currentIndex)); } else { System.out.println("No song is playing currently"); } }
3. 原有方法保留
addSong、checkSong、displaySongs方法无需修改,可正常使用。
注意事项
如果后续需要实现删除歌曲的功能,删除索引小于currentIndex的歌曲时,需要将currentIndex减1,避免播放索引错位。
内容的提问来源于stack exchange,提问作者ninesw
相关产品推荐
相关产品推荐

