How to Serialize ArrayList in Java?
Last Updated :
15 Dec, 2020
ArrayList is a class under the collections framework of java. It is present in java.util package. An ArrayList is a re-sizable array in java i.e., unlike an array, the size of an ArrayList can be modified dynamically according to our requirement. Also, the ArrayList class provides many useful methods to perform insertion, deletion, and many other operations on large amounts of data.
What is serialization?
To serialize an object means to convert its state to a byte stream so that the byte stream can be reverted back into a copy of the object. A Java object is serializable if its class or any of its superclasses implement either the java.io.Serializable interface or its sub interface, java.io.Externalizable. When an object is serialized, information that identifies its class is recorded in the serialized stream.
Serializing ArrayList:
In Java, the ArrayList class implements a Serializable interface by default i.e., ArrayList is by default serialized. We can just use the ObjectOutputStream directly to serialize it.
Java
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class ArrayListEx {
static void serializeArrayList()
{
ArrayList<String> namesList
= new ArrayList<String>();
namesList.add( "Geeks" );
namesList.add( "for" );
namesList.add( "Geeks" );
try {
FileOutputStream fos
= new FileOutputStream( "namesListData" );
ObjectOutputStream oos
= new ObjectOutputStream(fos);
oos.writeObject(namesList);
oos.close();
fos.close();
System.out.println( "namesList serialized" );
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
public static void main(String[] args) throws Exception
{
serializeArrayList();
}
}
|
Output:
Note:
All the elements stored in the ArrayList should also be serializable in order to serialize the ArrayList, else NotSerializableException will be thrown.
Share your thoughts in the comments
Please Login to comment...