简体   繁体   中英

Java toString() override for P

I am trying to print these songs from an array list which looks like this: After adding the songs, I have to remove one of the songs and display the songs left, but I am not sure how I would override the toString() method because my output looks like this

Output:

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());
  }
}

Just in the class Song add a method which has the name toString() which returns the name of the song.

public String toString(){ 
    return theMemberVariableWithSongNameInIt ;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM