Array of Object to String and String to Array of Object

class Book{
int book_id;
String title;
float price;

Book(int id, String title, float price){
this.book_id = id;
this.title = title;
this.price = price;
}

public String toString(){
return this.book_id+"#"+this.title+"#"+this.price+"@";
}

public static String ObjToString(Book c[]){
String str = new String();
for(int i=0;i<c.length;i++){
str = str+c[i];
}
return str;
}

public static Book[] StringToObj(String str){
String[] st = str.split("@");
Book b2[] = new Book[st.length];

for(int i=0; i<st.length;i++){
String st1[] = st[i].split("#");
b2[i] = new Book(Integer.parseInt(st1[0]),st1[1],Float.parseFloat(st1[2]));
}
return b2;
}

public static void main(String args[]){

Book b[] = new Book[3];

b[0] =new Book(1,"Java", 100);
b[1] = new Book(2,"ADA", 200);
b[2] = new Book(3,"SP", 300);


System.out.print(Book.ObjToString(b));
String str1 = ObjToString(b);

Book c[] = StringToObj(str1);
for(int i=0;i<c.length;i++){
System.out.print(c[i]);
}
}
}

No comments:

Post a Comment