Java – How to Serialize and De-Serialize ArrayList ?

In this article, we will discuss how to serialize list of objects and also de-serializing 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 :

  • Corresponding class should implement java.io.Serializable interface
  • For pre-defined in-built Java classes, it should be implementing java.io.Serializable interface
  • Exception: will be thrown if we try to serialize any class that doesn’t implement java.io.Serializable interface,
  • For those classes which doesn’t implement Serializable interface then NotSerializableException thrown during execution

1. Serializing ArrayList<String> :

  • So for serializing ArrayList of String object
  • Both ArrayList and String should be serializable and luckily in Java API, both
  • 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

1.1 Serialization of ArrayList of String objects :

  • Below program serializes 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

1.2 De-Serialization of ArrayList of String objects :

  • Below program de-serializes ArrayList of String objects

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 and 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

2. Serializing ArrayList<Customer> :

  • 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

2.1 Customer POJO

  • Customer POJO with three member variables
  • their getter & setters
  • finally implementing java.io.Serializable interface

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
				+ "]";
	}
}

2.2 Serialization of ArrayList of Customer objects :

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

SerializeArrayListOfCustomObjects.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 SerializeArrayListOfCustomObjects {

	public static void main(String[] args) {

		// create List &amp; 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

2.3 De-Serialization of ArrayList of Customer objects :

  • This class de-serializes list of custom Java objects, which is serialized from above Customer POJO

DeSerializeArrayListOfCustomObjects.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 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

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - Serialization interview question and answers
Java - How to construct a singleton class in a multi-threaded environment ?