beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

How to serialize ArrayList in java

By Chaitanya Singh | Filed Under: Java Collections

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<String> al=new ArrayList<String>();
       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<String> arraylist= new ArrayList<String>();
        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.

Enjoyed this post? Try these related posts

  1. ArrayList in java with example programs – Collections Framework
  2. Hashtable in java with example
  3. Java – Check if a particular element exists in LinkedList example
  4. Vector Iterator example in Java
  5. Java ArrayList ensureCapacity() Method example
  6. How to compare two ArrayList in Java

Comments

  1. craig says

    November 1, 2014 at 8:46 AM

    Very helpful code and straight to the point. thanks.

    Reply
  2. craig says

    November 2, 2014 at 3:12 AM

    the line : arraylist = (ArrayList)ois.readObject(); produces an unchecked conversion warning !!

    Reply
  3. Nitin says

    May 8, 2015 at 9:35 AM

    java.io.StreamCorruptedException: invalid type code: 0A
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1374)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
    at java.util.ArrayList.readObject(ArrayList.java:733)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1004)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1866)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1771)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1347)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)

    These Errors are coming from the reading line.

    Reply
  4. Sujit says

    July 14, 2015 at 8:39 AM

    It is working fine

    Reply
  5. Hema says

    September 17, 2015 at 10:07 AM

    What if we have a combination of Strings and Integer in the file when processing for de-serialization. As we declared the ArrayList arraylist as String.

    Reply
  6. Asrinivas says

    April 6, 2016 at 12:48 PM

    I am getting below exeception for the same

    java.io.EOFException
    at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
    at java.io.ObjectInputStream.readObject0(Unknown Source)
    at java.io.ObjectInputStream.readObject(Unknown Source)
    at com.arrays.DeSerializationClass.main(DeSerializationClass.java:17)

    Reply
  7. Akshay says

    June 9, 2016 at 1:16 PM

    how it will be done in case of arraylist of non-primitive data types(array list of an object)

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

  • Java Tutorial
  • OOPs Concepts

Java Collections

  • ArrayList
  • LinkedList
  • ArrayList vs LinkedList
  • Vector
  • ArrayList vs Vector
  • HashMap
  • TreeMap
  • LinkedHashMap
  • HashSet
  • TreeSet
  • LinkedHashSet
  • Hashtable
  • HashMap vs Hashtable
  • Queue
  • PriorityQueue
  • Deque & ArrayDeque
  • Iterator
  • ListIterator
  • Comparable Interface
  • Comparator Interface
  • Java Collections Interview Q

MORE ...

  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap