How to Serialize ArrayList in java with Example

One important point to note about ArrayList is that it is serializable by default. So in other words you do not need to implement Serializable interface explicitly in order to serialize an ArrayList. I have already shared how to synchronize ArrayList in java, In this post we will study how to serialize and deserialize an ArrayList object.

Serialization of ArrayList

Run the below example and it will create a file named inputfile  which will be having ArrayList object in form of Stream of bytes. We would be using "inputfile" at the receivers end to recreate the Object from stream of bytes.One important point is that we do not need to implement the Serializable interface in the below example because ArrayList is serialized by default.


import java.util.*;
import java.io.*;
 public class ArrayListSerialization {
    public static void main(String args[]) {
    
       ArrayList<String> al=new ArrayList<String>();
       al.add("Boston");
       al.add("Dallas");
       al.add("New York");

       try{
         FileOutputStream fos= new FileOutputStream("inputfile");
         ObjectOutputStream oos= new ObjectOutputStream(fos);
         oos.writeObject(al);
         oos.close();
         fos.close();
       }catch(IOException ioe){
            ioe.printStackTrace();
        }
  }
}

Deserialization of ArrayList


In this example we are retrieving the stream of bytes from input file which we have stored using the above example. We are typecasting the returned object to ArrayList and showing the elements of ArrayList.

Note : We are getting the same elements which are added to the ArrayList during serialization example.


import java.util.*;
import java.io.*;
 public class DeSerialization {
    public static void main(String args[]) {
    
       ArrayList<String> arraylist= new ArrayList<String>();
        try
        {
            FileInputStream fis = new FileInputStream("inputfile");
            ObjectInputStream ois = new ObjectInputStream(fis);
            arraylist = (ArrayList) ois.readObject();
            ois.close();
            fis.close();
         }catch(IOException ioe){
             ioe.printStackTrace();
             return;
          }catch(ClassNotFoundException c){
             System.out.println("Class not found");
             c.printStackTrace();
             return;
          }
        for(String str: arraylist){
            System.out.println(str);
        }
  }
}


Output

Boston
Dallas
New York



About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry