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.;
- Serialization and De-Serialization in Java
- Serialization with Aggregation (HAS-A relationship)
- Serialization with Inheritance (IS-A relationship)
- Importance of SerialVersionUID in Serialization
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.;
- ArrayList of String Object
- 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 & 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:
- Java – Serialization and De-Serialization Tutorial Index
- Java – Introduction to Serialization and De-Serialization
- Java – Serializable interface
- Java – Transient keyword with Serialization
- Java – Transient keyword with static variable in Serialization
- Java – Transient keyword with final variable in Serialization
- Java – Serializing a variable with transient modifier or keyword
- Java – Order of Serialization and De-Serialization
- Java – Serialization with Aggregation
- Java – Serialization with Inheritance
- Java – Externalization in detail
- Java – Serializable v/s Externalizable
- Java – Importance of SerialVersionUID in Serialization
- Java – Singleton Design pattern with Serialization
- Java – How to construct a singleton class in a multi-threaded environment ?
- Java – Singleton design pattern, restricting Object creation by overriding readResolve() method
- Java – How to stop Serialization ?
- Java – How to serialize and de-serialize ArrayList ?
- Java – Interview question & answers on Serialization and Externalization
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
Happy Coding !!
Happy Learning !!