Java toString()覆盖P

时间:2013-04-17 17:44:41

标签: java override tostring

我正在尝试从数组列表中打印这些歌曲,如下所示: 添加歌曲后,我必须删除其中一首歌并显示剩下的歌曲,但我不确定如何覆盖toString()方法,因为我的输出看起来像这样

输出:

com.tdd.bll.Song@5e6a13
com.tdd.bll.Song@862041
com.tdd.bll.Song@1af9d1c
com.tdd.bll.Song@73a35c
com.tdd.bll.Song@1ea25aa

@Test
public void AddSongTest() {
    moesList.addSong(new Song("Alone", "Tech N9ne"));
    moesList.addSong(new Song("Wings", "Macklemore"));
    moesList.addSong(new Song("One More Night", "Maroon 5"));
    moesList.addSong(new Song("Words I Never Said", "Lupe Fiasco"));
    moesList.addSong(new Song("Dumb It Down", "Lupe Fiasco"));
    moesList.addSong(new Song("Nobody's Perfect", "J.Cole"));
    assertEquals(6, moesList.songCount());
}



@Test
public void RemoveSongTest() {     
  AddSongTest();
  moesList.removeSong(1);
  assertEquals(5, moesList.songCount());
  moesList.SongsLeft();
}
}

public void removeSong(int songsNumber) {
  songs.remove(songsNumber);
}

public void SongsLeft(){
  //System.out.print(songs.iterator().next());
  Iterator<Song> iterator = songs.iterator();
  while (iterator.hasNext()) {
    System.out.println(iterator.next().toString());
  }
}

1 个答案:

答案 0 :(得分:1)

在类Song中添加一个名为toString()的方法,该方法返回歌曲的名称。

public String toString(){ 
    return theMemberVariableWithSongNameInIt ;
}