0

I have an array that I need to print, and I've already looked through stackoverflow so I know that I need to use toString so that I don't just print the hashcode, but for some reason it's still printing stuff like "music2.Music2@4162b8ce, music2.Music2@3852fdeb, music2.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));         
}

This is my array and the method that I am using to print it. Any help would be appreciated.

akash
  • 22,664
  • 11
  • 59
  • 87

5 Answers5

2

You should define toString() method in your Music2 class and print it in the way you like. I don't know how fields in your object are named exactly, but it can look like this:

public class Music2 {
    ...

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

After that your printMusic method will work as expected.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
0

You can declare a for each loop to display the property of music. This is the code

for (Music2 music : musiclist){
    System.out.println("Title: " + music.getTitle);
}
0

Because by default Arrays got toString() implementation of the Object class, that is:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

So you need to overwrite toString() in your Class

@Override
    public String toString() {
        return this.fieldNameone + " "+ this.fieldNametwo + " " + this.fieldNamethree + " ";
    }
Ankur Anand
  • 3,873
  • 2
  • 23
  • 44
0

If using Java8 you can use

Arrays.stream(musiclist).forEach(System.out::print)

but make sure that Music2 has an overriden method for toString()

Nitin Dandriyal
  • 1,559
  • 11
  • 20
0

In the Arrays.toString(musiclist) you are actually invoking toString() on each element of the array to compose the resulting string. So, if you override the basic Object toString() implementation in Music2 class you will get what you want

public class Music2 {
    .....
    @Override
    public String toString() {
        return "Music2{" + "title=" + title + ", group=" + group + ", year=" + year + '}';
    }
}
jsfviky
  • 183
  • 1
  • 11