This question already has answers here:
How do I print my Java object without getting “SomeType@2f92e0f4”?
                                
                                    (9个答案)
                                
                        
                3年前关闭。
            
        

我有一个需要打印的数组,并且已经查看了stackoverflow,所以我知道我需要使用toString以便不只是打印哈希码,但由于某种原因,它仍在打印诸如“ music2.Music2@4162b8cemusic2.Music2@3852fdebmusic2.Music2@509c6c30

Music2[] musiclist = new Music2[10];
musiclist[0] = new Music2("Pieces of You", "1994", "Jewel");
musiclist[1] = new Music2("Jagged Little Pill", "1995", "Alanis Morissette");
musiclist[2] = new Music2("What If It's You", "1995", "Reba McEntire");
musiclist[3] = new Music2("Misunderstood", "2001", "Pink");
musiclist[4] = new Music2("Laundry Service", "2001", "Shakira");
musiclist[5] = new Music2("Taking the Long Way", "2006", "Dixie Chicks");
musiclist[6] = new Music2("Under My Skin", "2004", "Avril Lavigne");
musiclist[7] = new Music2("Let Go", "2002", "Avril Lavigne");
musiclist[8] = new Music2("Let It Go", "2007", "Tim McGraw");
musiclist[9] = new Music2("White Flag", "2004", "Dido");

public static void printMusic(Music2[] musiclist) {
     System.out.println(Arrays.toString(musiclist));
}


这是我的数组以及我用来打印它的方法。任何帮助,将不胜感激。

最佳答案

您应该在toString()类中定义Music2方法,并以自己喜欢的方式打印它。我不知道对象中字段的确切命名方式,但是看起来像这样:

public class Music2 {
    ...

    @Override
    public String toString() {
        return this.artist + " - "+ this.title + " (" + this.year + ")";
    }
}


之后,您的printMusic方法将按预期工作。

10-07 15:11