HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Collections Framework / Java ArrayList / How to serialize and deserialize ArrayList in Java

How to serialize and deserialize ArrayList in Java

In Java, ArrayList class is serializable by default. It essentially means that we do not need to implement Serializable interface explicitly in order to serialize ArrayList.

We can directly use ObjectOutputStream to serialize ArrayList, and ObjectInputStream to deserialize an arraylist object.

Note – The elements stored in arraylist should also be serializable, else program will throw NotSerializableException.

1. Example to serialize ArrayList of strings

Given below is an example Java program to persist an arraylist of strings.

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class ArrayListExample 
{
    public static void main(String[] args) throws Exception 
    {
        ArrayList<String> namesList = new ArrayList<String>();
        
        namesList.add("alex");
        namesList.add("brian");
        namesList.add("charles");

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

Program output.

The list is serialized in project root folder.

ArrayList Serialized
ArrayList Serialized

2. Example to serialize ArrayList of objects

Given below is an example Java program to save an arraylist of Employee objects. Employee class implement Serializable interface.

import java.io.Serializable;

public class Employee implements Serializable {

    String id;
    String firstName;
    String lastName;

    //Getters and setters

    public Employee(String id, String firstName, String lastName) {
        super();
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
    }
}
public class ArrayListExample 
{
    public static void main(String[] args) throws Exception 
    {
        ArrayList<Employee> employees = new ArrayList<>();
        
        employees.add(new Employee("1", "lokesh", "gupta"));
        employees.add(new Employee("2", "brian", "motto"));

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

Notice if Employee class does not implement Serializable interface, we will recieve this error.

java.io.NotSerializableException: com.howtodoinjava.demo.model.Employee
	at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
	at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
	at java.util.ArrayList.writeObject(ArrayList.java:766)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1128)
	at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496)
	at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
	at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
	at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
	at com.howtodoinjava.demo.ArrayListExample.main(ArrayListExample.java:23)

3. Example to deserialize ArrayList

3.1. Deserialize list of strings

Java program to deserialize list of strings and verify list content.

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;

public class ArrayListExample 
{
    public static void main(String[] args) throws Exception 
    {
        ArrayList<String> namesList = new ArrayList<String>();
        
        try 
        {
            FileInputStream fis = new FileInputStream("listData");
            ObjectInputStream ois = new ObjectInputStream(fis);

            namesList = (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;
        }
        
        //Verify list data
        for (String name : namesList) {
            System.out.println(name);
        }
    }
}

Program output.

alex
brian
charles

3.1. Deserialize list of objects

Java program to deserialize list of objects and verify list content.

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;

public class ArrayListExample 
{
    public static void main(String[] args) throws Exception 
    {
        ArrayList<Employee> employees = new ArrayList<>();
        
        try 
        {
            FileInputStream fis = new FileInputStream("employeeData");
            ObjectInputStream ois = new ObjectInputStream(fis);

            employees = (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;
        }
        
        //Verify list data
        for (Employee employee : employees) {
            System.out.println(employee);
        }
    }
}

Program output.

Employee [id=1, firstName=lokesh, lastName=gupta]
Employee [id=2, firstName=brian, lastName=motto]

Happy Learning !!

Read More:

A Guide to Java ArrayList
ArrayList Java Docs

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Pedro

    July 29, 2019

    Podes me enviar o conteudo da employeeddata ?

    Obrigado

    • Lokesh Gupta

      July 30, 2019

      Everything is in the posted code itself.

  2. EJP

    January 21, 2019

    Why are you casting to ArrayList when you should be casting to ArrayList?

    • Jack

      April 16, 2020

      Why are you saying the same thing when you shouldn’t be saying the same thing?

Comments are closed on this article!

Search Tutorials

ArrayList Methods

  • ArrayList – Introduction
  • ArrayList – add()
  • ArrayList – addAll()
  • ArrayList – clear()
  • ArrayList – clone()
  • ArrayList – contains()
  • ArrayList – ensureCapacity()
  • ArrayList – forEach()
  • ArrayList – get()
  • Arraylist – indexOf()
  • Arraylist – lastIndexOf()
  • ArrayList – listIterator()
  • ArrayList – remove()
  • ArrayList – removeAll()
  • ArrayList – removeIf()
  • ArrayList – retainAll()
  • ArrayList – sort()
  • ArrayList – spliterator()
  • ArrayList – subList()
  • ArrayList – toArray()

ArrayList Examples

  • ArrayList – Initialize arraylist
  • ArrayList – Iteration
  • ArrayList – Add/replace element
  • ArrayList – Add multiple elements
  • ArrayList – Check empty list
  • ArrayList – Remove element
  • ArrayList – Replace element
  • ArrayList – Empty arraylist
  • ArrayList – Synchronized arraylist
  • ArrayList – Compare two lists
  • ArrayList – Remove duplicates
  • ArrayList – Merge two lists
  • ArrayList – Serialization
  • ArrayList – Swap two elements
  • Convert ArrayList to Array
  • Convert Array to ArrayList
  • Convert HashSet to ArrayList
  • Convert LinkedList to ArrayList
  • Convert Vector to ArrayList
  • ArrayList vs LinkedList
  • ArrayList vs Vector

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)