好吧,所以我看到一个示例,其中有一个名为Song的类,具有两个标题和持续时间,然后他又创建了一个类似ArrayList<Song> songs
的ArrayList,但是我的问题是为什么我们需要这样做,这真的让我感到困惑。
package linkedList.practic.task;
public class Song {
private String title;
private double duration;
public Song(String title, double duration) {
this.title = title;
this.duration = duration;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public double getDuration() {
return duration;
}
public void setDuration(double duration) {
this.duration = duration;
}
@Override
public String toString() {
return
"title='" + title + '\'' +
", duration='" + duration;
}
}
package linkedList.practic.task;
import java.util.*;
public class Album {
String name;
String artist;
private ArrayList<Song> songs;
public Album(String name, String artist) {
this.name = name;
this.artist=artist;
songs = new ArrayList<>();
}
public boolean addSong(String title, double duration){
if(findSong(title) == null){
this.songs.add(new Song(title, duration));
return true;
}
return false;
}
private Song findSong(String name){
for(Song checkSong : this.songs){
if(checkSong.getTitle().equals(name)){
return checkSong;
}
}
return null;
}
public boolean addToPlaylist(int trackNumber , LinkedList<Song> playlist){
int index=trackNumber-1;
if((index>=0)&&(index<this.songs.size())){
playlist.add(this.songs.get(index));
return true;
}
System.out.println("This album doesnot hava a track " + trackNumber);
return false;
}
public boolean addToPlaylist(String title, LinkedList<Song> playlist){
Song checkSong = findSong(title);
if(checkSong!=null){
playlist.add(checkSong);
return true;
}
System.out.println("The song " + title + " is not in this album");
return false;
}
public void printSongs(){
for(int i = 0; i<songs.size(); i++){
System.out.println(i+1+"."+ songs.get(i));
}
}
}