Mike Kogan
Mike Kogan

Reputation: 278

Serialize an ArrayList containing ArrayLists?

In an android app I need to persist some data to a file that is in an ArrayList of objects of type A. The objects of type A in ArrayList consist of standard primitive objects, except each A object also contains an ArrayList of objects of type B.

The B objects are also composed of primitive data types. Neither class A nor B has any particular code for implementing Serializable at this point.

My question is how should I go about writing this data to a file. Do I need to add specific support to serialize these objects? I suspect not since they only contain primitive data types, but OTOH I suspect I need to since ArrayList is not a primitive type itself.

Guidance is much appreciated. I want to do the simplest thing possible. I know I could write my own JSONSerializer code that manually serializes each field in class A, and invokes JSON serializer code from class B to serialize the ArrayList items, and stuff it all in a file. I also am not interested in running this all through SQLLite.

WHile I have found many posts on serializing arraylists I have found none for nested ArrayLists. Thanks in advance for the assist.

Upvotes: 1

Views: 548

Answers (2)

Jamel ESSOUSSI
Jamel ESSOUSSI

Reputation: 200

Use ObjectInputStream and ObjectOutputStream, something like:

public static void saveArrayListToFile(ArrayList<Book> books, String filePath)
{
    ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(filePath)));
    oos.writeObject(books);
    oos.close();
}

// ...

public static ArrayList<Book> loadArrayListFromFile(String filePath)
{
    ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(filePath)));
    try
    {
        return (ArrayList<Book>) ois.readObject();
    }
    finally
    {
        ois.close();
    }
}

Note that Book class must implements Serializable interface. I did not test the code, but it should work. You may need to try-catch for any exceptions in the code above.

Upvotes: 0

Ilya Gazman
Ilya Gazman

Reputation: 32271

If you want to use Serializable, you should have no problems, because ArrayList is Serializable. Just make sure your non primitive objects are Serializable too.

Upvotes: 2

Related Questions