Java – serialize the object containing the ArrayList object

public class User  implements  Serializable{
public class User  implements  Serializable{

    public String name;
    public String surname;
    public List<Picked> pickedBooks = new ArrayList<>();

    // Code omitted.
}

Then go to class:

public class Picked {

    public Book book;
    public int period;
    public int cost;

    // Code omitted.
}

And class books:

public class Book {

    public String name;
    public String bookTitle;
    public int howMany;

    // Code omitted.
}

So in the main, I create a new user and serialize it:

User user = new User();
user.setName("John");
user.setSurname("James");
String fileName = "data.bin";
try (ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(fileName))) {
    os.writeObject(user);
} catch (IOException ex) {
    Logger.getLogger(Library.class.getName()).log(Level.SEVERE,null,ex);
}

Everything is perfect, but if I do this:

Book book = new Book("Dan Brown","Angels and Demons",1);
Picked pck = new Picked(book,20,2);
user.add(pck);

Then I wanted to serialize the user object, and the program crashed The output I get is:

Solution

Picked and book also need to implement serializable

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>