Skip to main content

Serialize ArrayList in java

How to serialize ArrayList in Java

In this article, we are going to learn how to serialize ArrayList in Java. Also, we will see how to deserialize ArrayList in Java. To serialize or deserialize, the class must implement the java.io.Serializable interface. In our case, we can serialize ArrayList as ArrayList class implements Serializable Interface, See the hierarchy of ArrayList.
"Serialization is a process in which we convert the object into the byte stream and this stream of bytes can be stored into the file system/databases or can be placed onto the network for transmission from one place to another.
Deserialization is the reverse process of the Serialization. Deserialization is to get back the objects from the byte stream."

Content of the Article


How to serialize ArrayList of strings?

Let's start with a very basic example to serialize ArrayList of string objects. We can use the writeObject() method of ObjectOutputStream to serialize ArrayList in Java.

Java Serialize ArrayList Example 1: Serialize ArrayList of strings

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> languageList = new ArrayList<>(
            Arrays.asList("Java", "C++", "NodeJS", "JavaScript", "Python"));
            try {
                FileOutputStream fileOutputStream = new FileOutputStream("data");
                ObjectOutputStream objectOutputStream 
                    = new ObjectOutputStream(fileOutputStream);

                objectOutputStream.writeObject(languageList);

                objectOutputStream.close();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
}
In the above example, we serialize ArrayList of different programming languages using the writeObject() method. Run this program and see into your file system, a file named with the "data" will be created. Now, learn how to read that file and deserialize the ArrayList

Java Serialize ArrayList Example 2: Deserialize ArrayList of strings

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        try {
            FileInputStream fileInputStream = new FileInputStream("data");
            ObjectInputStream objectInputStream 
                = new ObjectInputStream(fileInputStream);

            ArrayList<String> arrayList 
                = (ArrayList<String>) objectInputStream.readObject();
            System.out.println(arrayList);

            fileInputStream.close();
            objectInputStream.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
Output
[Java, C++, NodeJS, JavaScript, Python]

How to serialize ArrayList of user-defined objects?

We can also serialize ArrayList of user-defined objects, but remember that the user-defined object must implement the Serializable interface. Otherwise, java.io.NotSerializableException will be raised. In our previous example, we have serialized the ArrayList of string objects and the String class implements Serializable interface.
"The java.io.Serializable interface is a marker interface, which tells that the object can be serialized or not."

Java Serialize ArrayList Example 3: Serialize ArrayList of user-defined objects

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;

class Book implements Serializable {
    private String name;
    private Integer price;
    private String edition;

    public Book(String name, String edition, Integer price) {
        this.name = name;
        this.price = price;
        this.edition = edition;
    }

    @Override
    public String toString() {
        return "[ name : " + name + ", edition : " + edition + ", " 
                                + "price : " + price + "]";
    }
}

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<Book> books = new ArrayList<>();
        books.add(new Book("Learn Java", "8th", 550));
        books.add(new Book("Coding in Python", "5th", 750));
        books.add(new Book("Data Structures", "2nd", 400));
        books.add(new Book("Introduction to Database", "4th", 500));

        // Serialize ArrayList of user-defined objects
        try {
            FileOutputStream fileOutputStream = new FileOutputStream("books-file");
            ObjectOutputStream objectOutputStream 
                = new ObjectOutputStream(fileOutputStream);

            objectOutputStream.writeObject(books);

            fileOutputStream.close();
            objectOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Deserialize ArrayList of user-defined objects
        try {
            FileInputStream fileInputStream = new FileInputStream("books-file");
            ObjectInputStream objectInputStream 
                = new ObjectInputStream(fileInputStream);

            ArrayList<Book> deserializedBooks 
                = (ArrayList<Book>) objectInputStream.readObject();
            for (Book book : deserializedBooks) {
                System.out.println(book);
            }

            fileInputStream.close();
            objectInputStream.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
Output
[ name : Learn Java, edition : 8th, price : 550]
[ name : Coding in Python, edition : 5th, price : 750]
[ name : Data Structures, edition : 2nd, price : 400]
[ name : Introduction to Database, edition : 4th, price : 500]

Importance of "transient" keyword in Serialization

In the above program, all the fields of Book class are serialized and stored in the file. If we do not want to serialize any field then we can make that field transient. The transient keyword is used to make any field not to be serialized into the stream of bytes at the time of serialization.
Syntax
transient int price;

Java Serialize ArrayList Example 4: Serialize ArrayList of user-defined objects with few transient fields

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;

class Book implements Serializable {
    private String name;
    private Integer price;
    transient private String edition;

    public Book(String name, String edition, Integer price) {
        this.name = name;
        this.price = price;
        this.edition = edition;
    }

    @Override
    public String toString() {
        return "[ name : " + name + ", edition : " + edition + ", " 
                                + "price : " + price + "]";
    }
}

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<Book> books = new ArrayList<>();
        books.add(new Book("Learn Java", "8th", 550));
        books.add(new Book("Coding in Python", "5th", 750));
        books.add(new Book("Data Structures", "2nd", 400));
        books.add(new Book("Introduction to Database", "4th", 500));

        // Serialize ArrayList of user-defined objects
        try {
            FileOutputStream fileOutputStream = new FileOutputStream("books-file");
            ObjectOutputStream objectOutputStream 
                = new ObjectOutputStream(fileOutputStream);

            objectOutputStream.writeObject(books);

            fileOutputStream.close();
            objectOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Deserialize ArrayList of user-defined objects
        try {
            FileInputStream fileInputStream = new FileInputStream("books-file");
            ObjectInputStream objectInputStream 
                = new ObjectInputStream(fileInputStream);

            ArrayList<Book> deserializedBooks 
                = (ArrayList<Book>) objectInputStream.readObject();
            for (Book book : deserializedBooks) {
                System.out.println(book);
            }

            fileInputStream.close();
            objectInputStream.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
Output
[ name : Learn Java, edition : null, price : 550]
[ name : Coding in Python, edition : null, price : 750]
[ name : Data Structures, edition : null, price : 400]
[ name : Introduction to Database, edition : null, price : 500]
As we can see from the output, the edition field remains null after the deserialization. Because at the time of serialization of ArrayList, the edition field could not be serialized into the file as it is declared as transient.

Related Posts:


Comments