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

Popular posts from this blog

How HashMap works internally in java

How Hashmap works Internally in Java In this article, we are going to see how HashMap internally works in java. Also, we will have a look at what Java 8 made changes on the internal working of Hashmap to make it faster. What is Hashmap and Hashing in java? How Hashmap works Internally in Java is majorly dependent upon the Hashing Principle. So, Before going to learn how HashMap works internally in java, lets first understand what is HashMap and hashing. HashMap : A HashMap is a map used to store mappings of key-value pairs. Also, it works on the Principle of Hashing. To know more about the HashMap, visit this article: HashMap in Java Hashing Principle : Simply, Hashing is a method used to produce an integer value from an object and this integer value known as the hash value. In HashMap, the key object is used for Hashing.
Internal Struture of the HashMap in java For internal working of HashMap, HashMap maintains an array of bucket, each bucket is a linked-list and linked list is a li…

HashMap in Java

HashMap in Java In this article, we are going to learn about the most important class of Java known as HashMap. HashMap in java is the most used map interface and it is used in our regular or day-to-day programming practices.
What is HashMap in java? Lets first start with basic definition of HashMap,
HashMap is a map which store key-value pair, where each key is mapped with a value.
HashMap defined in java.util package and implements map interface which provides functionalities to perform basic operation like store, retrieve, size of the map etc. It is a part of Java Collection Framework. Time complexity of HashMap in Java? : Time complexity to store and retrieve data from the HashMap is O(1) in the Best Case. But it can be O(n) in the worst case and after the changes made in Java 8 the worst case time complexity can be O(log n) atmost. Internal working of HashMap in java HashMap maintains an array of the buckets, where each bucket is a linked-list and the linked list is a list of…

ArrayList in Java

ArrayList in Java In this article, we are going to discuss ArrayList in Java. ArrayList is a class from the Java Collection Framework and widely in our programs. We use ArrayList as a substitute for the array. So, it is important to know ArrayList in detail. We are going to see what is ArrayList in Java, how we can create the instance of ArrayList and the methods provided by the ArrayList in Java.

If you already familiar to ArrayList, you may learn common programs related to ArrayList.
Table of ContentsWhat is ArrayList in Java?Hierarchy of the ArrayList in java?How to create objects of ArrayList in Java?How to create an ArrayList of Custom Objects?How to iterate ArrayList in Java?How to get the elements by index from ArrayList in Java?How to check whether an elements is stored in the ArrayList in Java?How to remove elements from the ArrayList in Java?Few more methods of ArrayList in Java?
What is ArrayList in Java? ArrayList in Java is a List in which we can store and retrieve elemen…