如何使用音乐应用程序的集合

时间:2018-06-19 09:33:04

标签: java collections

我正在为我的学校写一个基本的音乐应用程序。我们老师问我们的是,我们需要创建三个班级;歌曲,播放列表和MusicCollection。播放列表对象包含歌曲,音乐集合包含播放列表。我编写了我的Song类,也是PlayList类的重要部分。但有两种方法我不太了解。一个是sortByName,另一个是sortByPlayingTime。我需要使用集合,直到现在我才写东西,但它不起作用。你看看吗?

public class PlayList {

private String playListName;
private ArrayList<Song> songsPlayList = new ArrayList<>();

public PlayList(String playListName) {
    this.playListName = playListName;
}

public void addSong(Song songObject){
    songsPlayList.add(songObject);
}

public void removeSong(Song songObject) {
    songsPlayList.remove(songObject);
}

public void countOfPlaylist(){
    System.out.println("You have " + songsPlayList.size() + " songs on your list!");
}

public void displayPlayList(){
    for (int i =0;i<songsPlayList.size();i++){
        System.out.println((i+1) + ". " + songsPlayList.get(i));
    }
}

public void sortByName(){
    System.out.println("You can see your list as sorted by name.\n");
    Collections.sort(song); //this code give an error!
    for (Song temp : songsPlayList){
        System.out.println(temp);
    }
}

public void sortByPlayingTime(){
    System.out.println("Your playlist sorted by playing time.");
    //I stock here.
}

同样在我的MusicCollection类中,我需要做同样的事情。将歌曲添加到播放列表很容易,但现在我需要选择(或说)我需要添加歌曲的播放列表。我写了我的方法,但尚未定义。我需要你的帮助:)

这是我的MusicCollection类:

public class MusicCollection {

private String musicCollectionName;
private ArrayList<PlayList> collection = new ArrayList<>();

public MusicCollection(String musicCollectionName) {
    this.musicCollectionName = musicCollectionName;
}

public void addSongToPlayList(String playListName,Song songObject){


}

public void removeSongFormPlaylist (String playListName, Song songObject){

}

public void addPlayList (PlayList  playlistObject){

}

public void removePlayList (PlayList  playlistObject){

}

public int countOfPlaylistsInCollection(){

    return 0;
}

public int countsOfSongsInPlayList (String playlistName){

    return 0;
}

public void displayPlayListInCollection(){

}

public void displaySongsFromPlaylist (String playlistName){

}

}

2 个答案:

答案 0 :(得分:0)

Collections.sort(song);

您的song变量在哪里?我想你必须排序songsPlayList。你必须为你的Song课程编写比较器。例如,实现Comparable接口。有关比较器的更多信息,请参阅this articlethis question

答案 1 :(得分:0)

您需要Comparator<Song>来比较两首歌曲的播放时间:

public static final Comparator<Song> BY_PLAYINGTIME = new Comparator<Song>() {
    @Override
    public int compare(Song a, Song b) {
        return a.getPlayingTime().compareTo(b.getPlayingTime());
    }
};

然后,您可以使用以下方式对列表进行排序:

Collections.sort(songsPlayList, BY_PLAYINGTIME);