所以我创建了3类Song类Album类和Main类,Song类标题和持续时间变量,Album类具有ArrayList<Song>
此类具有方法addSong(Song song)
,其返回类型为boolean fo,该方法在做什么,如果Song是已经是列表,则不打算添加它,这意味着它返回false否则它将添加,因此从Main类中,我正在调用此方法。 BUT问题是它的输出像这样linkedList.practic.task.Song@76fb509a
Song.java
package linkedList.practic.task;
public class Song {
private String title;
private String duration;
public Song(String title, String duration) {
this.title = title;
this.duration = duration;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
}
Album.java
package linkedList.practic.task;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class Album {
private ArrayList<Song> songs;
public Album() {
songs = new ArrayList<>();
}
public boolean addSong(Song song){
if(!this.songs.contains(song)){
this.songs.add(song);
return true;
}
return false;
}
public void printSongs(){
Iterator<Song> iterator = songs.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next() + " ");
}
}
}
Main.java
package linkedList.practic.task;
import java.util.Scanner;
public class Main {
static Scanner scan = new Scanner(System.in);
static Album album = new Album();
public static void main(String[] args) {
boolean flag = true;
while(flag){
System.out.println("Enter your choice");
int action = scan.nextInt();
switch (action){
case 0:
flag = false;
break;
case 1:
addSong();
break;
case 2:
album.printSongs();
}
}
}
private static void addSong(){
System.out.println("Enter the name of the song");
String name = scan.nextLine();
scan.nextLine();
System.out.println("Enter the duration of song");
String duration = scan.nextLine();
if(album.addSong(new Song(name, duration))){
System.out.println( name + " is added to the list");
}
else{
System.out.println( name + " is already in the list");
}
}
}
也添加了歌曲的非打印名称后的歌曲,仅打印is added to the list
,其他部分相同
您必须重写Song类的toString方法
您需要在Song类中重写toString()方法,因为默认情况下,Object类上的实现会返回object的ID。这样的事情将为您工作-