BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

How to serialize ArrayList in java

By Chaitanya Singh | Filed Under: 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<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.

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 Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap