开发者

How to store an array of object types as a string so another class can later call and print that string. java

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.


StringBuilder sb = new StringBuilder();
sb.append(song1.toString());
sb.append(" some delimiter ");
sb.append(song2.toString());

System.err.println(sb.toString());

Is that what you need?

EDIT: It's possible to do it this way as well sb.append(song1); as StringBuilder will automatically call toString() if an unknown Object is passed.


You can make a 2D array and store the Object in [i][0] and the "string" you want to call in [i][1].


If I understand you correctly, you want to be able to read your objects from the string back. If that is the case, what you're trying to do is called Serialization, and here's a simple example


Just create a second array or list of type String and iterate over the first array using String.valueOf(...) to store the objects as Strings in the new container.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜