ArrayList Serialization with Multiple Instances/Extends

572 views Asked by At

Lets say I have an ArrayList that contains instances of multiple classes that extends from the "People"(Lets call it that) class.

An example: Example two Strings are Name and Course Name

ArrayList<People> people = new ArrayList<>();
people.add(new Teacher("Mrs. Doe","Math"));
people.add(new Student("Bob","Math"));
people.add(new Student("Sue","Math"));
people.add(new Student("Joe","Math"));

Quick example of the structure of these classes:

 abstract class People implements Serializable
    {
        String name;
        String course;
        ...
        private People(String newName, String newCourse)
        {
            this.name = newName;
            ...
        }
        @Override
        public String toString(){return...}
    }
    public class Teacher extends People
    {
        public class Teacher... yada-yada{
        super(variables)}
        @Override String toString(){return...}...
    }
    public class Student extends People
    {
        public class Teacher... yada-yada{
        super(variables)}
        @Override String toString(){return...}...
    }

Is it possible to output the ArrayList to a file without getting any errors(hehe)?

Error: java.io.NotSerializableException: mvc.Model

It yells at me for this line: out.writeObject(people);

Is that not allowed? Is life not this easy? Could these extra instances be interfering with this? I've done some quick dirty code with making a new list without any extra instances and it worked.

Thanks in advanced!

2

There are 2 answers

0
Jake Chasan On BEST ANSWER

Have you tried writing the array list without the toString. You could serialize the class, then write the ArrayList, just as you would write any other object.

Writing the ArrayList:

    FileOutputStream fos = new FileOutputStream(filename);
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(ARRAY_NAME);

Just remember to include the following to decode the serialization:

private static final long serialVersionUID = 123456;

Reading the ArrayList: When trying to read the ArrayList back in, you could do this: (as long as it is from the same serialized class)

    FileInputStream fis = new FileInputStream(filename);
    ObjectInputStream ois = new ObjectInputStream(fis);
    ARRAY_NAME = (ARRAY_TYPE_CAST)ois.readObject();
0
Ankit Rustagi On

Is it possible to output the ArrayList to a file without getting any errors(hehe)?

Extend Arraylist and implement java.io.Serializable like this -

public class MyList extends ArrayList implements java.io.Serializable

For you to serialize an object you need to extend java.io.Serializable. Since you need to serialize ArrayList, simply extend it.

PS - Keeping your question simple would get you more help.