创建了以下类,现在没有接口/抽象类:
我尝试了一个ArrayList,但是当我添加另一张CD时它会被覆盖。我需要一种数据类型,它存储带有另一个数组链接的数据。例如:存储CD1的艺术家和标题,并链接到包含CD1中所有歌曲的另一个数组。
谢谢
来自Test类的代码:
Artist aArtist = new Artist("artist1");
CD aCD = myMusic.addCD(aArtist, "CD1");
aCD.addSong(aArtist, "song1", "1:00");
aArtist = new Artist("artist2");
CD aCD = myMusic.addCD(aArtist, "CD2"); //Overwrites arraylist from CD1
aCD.addSong(aArtist, "song2", "2:00");
我在类Music和class CD中更改了我的ArrayLists ...我认为有一种更简单的方法来解决该教程,但这里是代码:(输出所有保存的歌曲和CD标题)
课堂音乐:
import java.util.ArrayList;
public class Music {
private ArrayList<CD> myCDs = new ArrayList<CD>();
public CD addCD(Artist anArtist, String cdTitle) {
CD aCD = new CD(anArtist, cdTitle);
myCDs.add(aCD);
return aCD;
}
public void showData() {
for (int i = 0; i < myCDs.size(); i++) {
for (int j = 0; j < myCDs.get(i).getMyCD().size(); j++) {
System.out.println(myCDs.get(i).getMyCD().get(j).getSong());
}
}
}
}
课程CD:
import java.util.ArrayList;
public class CD {
private String cdTitle;
private ArrayList<Song> myCD = new ArrayList<Song>();
public CD(Artist aArtist, String cdTitle) {
setMyCD(aArtist, cdTitle);
}
public ArrayList<Song> getMyCD() {
return myCD;
}
public String getMyCDtitle() {
return cdTitle;
}
public void setMyCD(Artist anArtist, String cdTitle) {
this.cdTitle = anArtist.getName() + ": " + cdTitle;
}
public void addSong(Artist anArtist, String aTitle, String aDuration) {
myCD.add(new Song(anArtist, aTitle, aDuration));
}
}
课堂歌曲:
public class Song {
private String song;
public String getSong() {
return song;
}
public void setSong(String song) {
this.song = song;
}
public Song(Artist anArtist, String songtitle, String aDuration) {
Duration songDuration = new Duration(aDuration);
setSong(anArtist.getName() + ": " + songtitle + " ("
+ songDuration.getSongDuration() + ")");
}
}
总的来说:你会如何解决这样的项目?
我很感激每个建议或uml图。
答案 0 :(得分:1)
这可能是aArtist = new Artist("artist2");
CD aCD = myMusic.addCD(aArtist, "CD2"); //Overwrites arraylist from CD1
aCD.addSong(aArtist, "song2", "2:00");
的问题
您使用相同的Artist对象。如果你发布你的addCD方法实现,它将对我们更开放。