2、使用 list 集合整理音乐播放列表,请彭彭老师检查,感谢!
来源:14-17 测评作业
mottoyin
2025-02-19
package com.imooc.chapter14test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class SongSetTest {
public static void main(String[] args) {
//定义歌曲播放列表
List<Song> songList = new ArrayList<>();
//定义原有歌曲
Song song1 = new Song("好运来","祖海","春节大联唱","MP3");
Song song2 = new Song("听海","张惠妹","听海","无损");
Song song3 = new Song("Me and Mrs Jones","Michael Bubble","New York Live","无损");
songList.add(song1);
songList.add(song2);
songList.add(song3);
//定义小慕的歌单
Song song4 = new Song("又见炊烟","王菲","非常传奇","无损");
Song song5 = new Song("可能","程响","可能","无损");
Song song6 = new Song("大风吹","王赫野","大风吹","无损");
Song song7 = new Song("今天","刘德华","真永远","无损");
Song song8 = new Song("再回首","姜育恒","多年以后.再回首","无损");
songList.add(song4);
songList.add(song5);
songList.add(song6);
songList.add(song7);
songList.add(song8);
System.out.println("您现有歌单如下:");
for (Song song:
songList) {
System.out.println("歌名: " + song.getName() + " 歌手: " + song.getSinger() + " 专辑:" + song.getAlbum() + " 音质: " + song.getQuality());
}
System.out.println("歌单总共有: " + songList.size() + "首歌曲");
//假定我要删除好运来,大风吹
//定义迭代器
Iterator it = songList.iterator();
while (it.hasNext()) {
Song next = (Song) it.next(); //强制转型至Song类型
if(next.getName().equals("好运来")||next.getName().equals("大风吹")) {
it.remove();
}
}
System.out.println("删除后歌单总共有: " + songList.size() + "首歌曲");
}
}
//使用迭代器进行遍历元素删除是安全的,不会遇到ConcurrentModificationException的问题,但是使用foreach循环就会,原因是foreach是基于迭代器实现的,删除时迭代器并不知道集合结构发生变化,所以会抛出错误
写回答
1回答
-
彭彭老师
2025-02-20
同学没有上传 Song 类,程序逻辑没有问题
00
相似问题