How to serialize and de-serialize ArrayList in Java

In this article, we will discuss how to serialize list of objects and also deserializing the same.

Already we have seen how to serialize and de-serialize objects in Java i.e.;

 

When we discussed above topics, we concentrated only on single Object i.e.; POJO (Plain Old Java Object)

Here, we will extend our demo example and discuss how to serialize and de-serialize list of Objects i.e.;

  1. ArrayList of String Object
  2. ArrayList of Custom Java object

 

Rule to serialize and de-serialize any object:

  • Corresponsding class should implement java.io.Serializable interface
  • For pre-defined in-built Java classes, it should be implementing java.io.Serializable interface

Exception: If we try to serialize any class that doesn’t implement java.io.Serializable interface, then an exception will be thrown stating reason as “NotSerializableException

 

So, for serializing ArrayList of String object –> both ArrayList and String should be serializable

  • ArrayList is by default implements java.io.Serializable interface
  • Also, String class implements java.io.Serializable interface

 

Let us focus on one simple Java program to serialize and de-serialize ArrayList of String objects

Serialization of ArrayList of String objects

SerializeArrayListOfStringObjects.java

package in.bench.resources.serialize.deserialize.arraylist;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class SerializeArrayListOfStringObjects {

	public static void main(String[] args) {

		// create ArrayList and inserts values
		List<String> leadersOfHistory = new ArrayList<String>();

		// add values to ArrayList
		leadersOfHistory.add("Joseph Stalin");
		leadersOfHistory.add("Adolf Hitler");
		leadersOfHistory.add("Benito Mussolini");
		leadersOfHistory.add("Napoléon Bonaparte");
		leadersOfHistory.add("Vladimir Putin");
		leadersOfHistory.add("Fidel Castro");
		leadersOfHistory.add("Robert Mugabe");


		// creating output stream variables
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;

		try {
			// for writing or saving binary data
			fos = new FileOutputStream("SaveArrayList.ser");

			// converting java-object to binary-format 
			oos = new ObjectOutputStream(fos);

			// writing or saving ArrayList values to stream
			oos.writeObject(leadersOfHistory);
			oos.flush();
			oos.close();
		} 
		catch (FileNotFoundException fnfex) {
			fnfex.printStackTrace();
		}
		catch (IOException ioex) {
			ioex.printStackTrace();
		}

		System.out.println("ArrayList object saved to SaveArrayList.ser file");
	}
}

Output:

ArrayList object saved to SaveArrayList.ser file

 

 

De-Serialization of ArrayList of String objects

Below program de-serializes “ArrayList of String objects”, which is serialized using above class

DeSerializeArrayListOfStringObjects.java

package in.bench.resources.serialize.deserialize.arraylist;

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

public class DeSerializeArrayListOfStringObjects {

	public static void main(String[] args) {

		// creating input stream variables
		FileInputStream fis = null;
		ObjectInputStream ois = null;

		// creating List reference to hold AL values after de-serialization 
		List<String> leadersOfHistory = null;

		try {
			// reading binary data
			fis = new FileInputStream("SaveArrayList.ser");

			// converting binary-data to java-object
			ois = new ObjectInputStream(fis);

			// reading object's value and casting ArrayList<String>
			leadersOfHistory = (ArrayList<String>) ois.readObject();
		} 
		catch (FileNotFoundException fnfex) {
			fnfex.printStackTrace();
		}
		catch (IOException ioex) {
			ioex.printStackTrace();
		} 
		catch (ClassNotFoundException ccex) {
			ccex.printStackTrace();
		}

		System.out.println("ArrayList object de-serialized from SaveArrayList.ser file\n");

		// iterating & printing ArrayList values to console
		for(String leader : leadersOfHistory){
			System.out.println(leader);
		}
	}
}

Output:

ArrayList object de-serialized from SaveArrayList.ser file

Joseph Stalin
Adolf Hitler
Benito Mussolini
Napoléon Bonaparte
Vladimir Putin
Fidel Castro
Robert Mugabe

 

 

We will move on and see one more demo example on serializing and de-serializing ArrayList of custom Java object

What it means?

In above example, Serialization and De-serialization of ArrayList of String objects where both ArrayList and String classes are Serializable (by default)

But when we try to serialize and de-serialize ArrayList of custom Java object, then both ArrayList and custom Java object should be Serializable, otherwise “NotSerializableException” is thrown

By default, ArrayList implements java.io.Serializable interface. So, we need to implement java.io.Serializable interface for custom Java class

 

 

Let us move on and see demo example for serializing and de-serializing ArrayList of custom Java objects

Customer POJO with three member variables and their getter & setters

Customer.java

package in.bench.resources.serialize.deserialize.arraylist;

import java.io.Serializable;

public class Customer implements Serializable {

	// SerialVersionUID
	private static final long serialVersionUID = 19L;

	// member variables
	int customerId;
	String customerName;
	int customerAge;

	// 3-arg parameterized constructor
	public Customer(int customerId, String customerName, int customerAge) {
		this.customerId = customerId;
		this.customerName = customerName;
		this.customerAge = customerAge;
	}

	// overriding toString() method
	@Override
	public String toString() {
		return "Customer [customerId=" + customerId + ","
				+ " customerName=" + customerName + ","
				+ " customerAge=" + customerAge
				+ "]";
	}
}

 

SerializeArrayListOfCustomObjects.java

Below class serializes list of custom Java objects (i.e.; Customer class which is implementing java.io.Serializable interface)

package in.bench.resources.serialize.deserialize.arraylist;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class SerializeArrayListOfCustomObjects {

	public static void main(String[] args) {

		// create List & ArrayList reference to store customers
		List<Customer> listOfCustomers = new ArrayList<Customer>();

		// create customer objects using constructor initialization
		Customer napoleon = new Customer(1814, "Napoleon Bonaparte", 52);
		Customer mussolini = new Customer(1943, "Benito Mussolini", 62);
		Customer hitler = new Customer(1945, "Adolf Hitler", 56);
		Customer stalin = new Customer(1952, "Joseph Stalin", 75);

		// add customer objects to ArrayList
		listOfCustomers.add(hitler);
		listOfCustomers.add(stalin);
		listOfCustomers.add(mussolini);
		listOfCustomers.add(napoleon);


		// creating output stream variables
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;

		try {
			// for writing or saving binary data
			fos = new FileOutputStream("ArrayListOfCustomer.ser");

			// converting java-object to binary-format 
			oos = new ObjectOutputStream(fos);

			// writing or saving ArrayList values to stream
			oos.writeObject(listOfCustomers);
			oos.flush();
			oos.close();
		} 
		catch (FileNotFoundException fnfex) {
			fnfex.printStackTrace();
		}
		catch (IOException ioex) {
			ioex.printStackTrace();
		}

		System.out.println("ArrayList of Customer objects saved to "
				+ "ArrayListOfCustomer.ser file");
	}
}

Output:

ArrayList of Customer objects saved to ArrayListOfCustomer.ser file

 

 

DeSerializeArrayListOfCustomObjects.java

This class de-serializes the list of custom Java objects (which is serialized from above class)

package in.bench.resources.serialize.deserialize.arraylist;

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

public class DeSerializeArrayListOfCustomObjects {

	public static void main(String[] args) {

		// creating input stream variables
		FileInputStream fis = null;
		ObjectInputStream ois = null;

		// creating List reference to hold AL values after de-serialization 
		List<Customer> listOfCustomers = null;

		try {
			// reading binary data
			fis = new FileInputStream("ArrayListOfCustomer.ser");

			// converting binary-data to java-object
			ois = new ObjectInputStream(fis);

			// reading object's value and casting ArrayList<Customer>
			listOfCustomers = (ArrayList<Customer>) ois.readObject();
		} 
		catch (FileNotFoundException fnfex) {
			fnfex.printStackTrace();
		}
		catch (IOException ioex) {
			ioex.printStackTrace();
		} 
		catch (ClassNotFoundException ccex) {
			ccex.printStackTrace();
		}

		System.out.println("ArrayList object de-serialized from "
				+ "ArrayListOfCustomer.ser file\n");

		// iterating & printing ArrayList values to console
		for(Customer customer : listOfCustomers){
			System.out.println(customer);
		}
	}
}

Output:

ArrayList object de-serialized from ArrayListOfCustomer.ser file

Customer [customerId=1945, customerName=Adolf Hitler, customerAge=56]
Customer [customerId=1952, customerName=Joseph Stalin, customerAge=75]
Customer [customerId=1943, customerName=Benito Mussolini, customerAge=62]
Customer [customerId=1814, customerName=Napoleon Bonaparte, customerAge=52]

 

Conclusion:

Thus, it is very easy to serialize and de-serialize any object in Java provided if it’s corresponding class implements Serializable interface

 

References:

https://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html
https://docs.oracle.com/javase/7/docs/platform/serialization/spec/serial-arch.html
https://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html
https://docs.oracle.com/javase/7/docs/api/java/io/ObjectInputStream.html
https://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html
https://docs.oracle.com/javase/7/docs/api/java/io/FileInputStream.html
https://docs.oracle.com/javase/tutorial/collections/intro/
https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
https://docs.oracle.com/javase/tutorial/collections/interfaces/list.html
https://docs.oracle.com/javase/tutorial/collections/implementations/list.html
https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html

 

Read Also:

 

Happy Coding !!
Happy Learning !!