Organizational Research By

Surprising Reserch Topic

Experts Most Trusted Topic


How to serialize ArrayList in java


ArrayList is serializable by default. This means you need not to implement Serializable interface explicitly in order to serialize an ArrayList. In this tutorial we will learn how to serialize and de-serialize an ArrayList.

Example:

Serialization: Run the below class and it will create a file myfile which will be having ArrayList object in form of Stream of bytes. We would be using ‚Äúmyfile‚ÄĚ at the receivers end to recreate the Object from stream of bytes. Note: We did not implemented the Serializable interface in the below class because ArrayList is already been serialized by default.

package beginnersbook.com;
import java.util.ArrayList;
import java.io.*;
public class ArrayListSerialization
{
   public static void main(String [] args)
   {
       ArrayList al=new ArrayList();
       al.add("Hello");
       al.add("Hi");
       al.add("Howdy");

       try{
         FileOutputStream fos= new FileOutputStream("myfile");
         ObjectOutputStream oos= new ObjectOutputStream(fos);
         oos.writeObject(al);
         oos.close();
         fos.close();
       }catch(IOException ioe){
            ioe.printStackTrace();
        }
   }
}
De-Serialization:

In this class we are retrieving the stream of bytes from myfile which we have stored using the above class. We are type casting the returned object to ArrayList and displaying the elements of ArrayList. Observe the output: We are getting the same elements which we have added to the ArrayList before the serialization.

package beginnersbook.com;
import java.io.*;
import java.util.ArrayList;
public class DeSerializationClass
{
    public static void main(String [] args)
    {
        ArrayList arraylist= new ArrayList();
        try
        {
            FileInputStream fis = new FileInputStream("myfile");
            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 tmp: arraylist){
            System.out.println(tmp);
        }
   }
}
Output:

Hello
Hi
Howdy
That’s all I have for the topic serialization of ArrayList. Please let me know if you have any questions.

asked Jun 11, 2015 in Java Interview Questions by rajesh
0 votes
146 views



Related Hot Questions



Walkin Jobs Opening



Government Jobs Opening


...