I have an array of different objects with different data types I want to be able to store the objects of the array as a string so a different method later can use it.
import java.util.Arrays;
public class Music {
private String songTitle;
private double songLength;
private int rating;
public Music(String songTitle, double songLength, int rating) {
this.songTitle = songTitle;
this.songLength = songLength;
this.rating = rating;
}
public String getsongTitle()
{
return songTitle;
}
public double getsongLength()
{
return songLength;
}
public int rating()
{
return rating();
}
@Override
public String toString() {
return "music{"+ "songTitle= " + songTitle + ", songLength= "
+ songLength + ",rating=" + rating + '}';
}
//constructors for music objects
static Music song1 = new Music ("song name", 5.32, 10);
static Music song2 = new Music ("billy",1.2, 8 );
static Music song3 = new Music ("hello", 1.5, 9 );
static //Create array and make posistion 0 = song1
Music[] songDetails ={song1,song2,song3};
public static void main(String[] args) {
System.out.println(Arrays.toString(songDetails));
System.out.println(songDetails[0]);
}
}
So it pretty easy to just print the array out but how do I store it as a String to call it later.
I’ve been stuck on this for a few hours now. I looked into using stringbuilder but I couldn’t get the result I was after.
Edit for clarity
Sorry you’re both right it is a little unclear.
What I want is to declare an empty string and save the contents of the array to that string. but when I try to do that eclipse tells me. “Type mismatch: cannot convert from Music to String”
So that’s the real problem. As to the methods and class bit well I’m still learning methods and invoking and calling them so i’ll go back and study that myself a bit.
Is that what you need?
EDIT: It’s possible to do it this way as well
sb.append(song1);as StringBuilder will automatically calltoString()if an unknown Object is passed.