DEV Community

aryan
aryan

Posted on

1 2

How to serialize and deserialize 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.

See original article: https://www.java8net.com/2020/03/serialize-arraylist-in-java.html

Serialization of ArrayList:

ArrayList arrayList = new ArrayList<>(
Arrays.asList("A", "B", "C", "D", "E"));
try {
FileOutputStream fileOutputStream = new FileOutputStream("data");
ObjectOutputStream objectOutputStream
= new ObjectOutputStream(fileOutputStream);

  objectOutputStream.writeObject(arrayList);

  objectOutputStream.close();
  fileOutputStream.close();
Enter fullscreen mode Exit fullscreen mode

} catch (IOException e) {
e.printStackTrace();
}

Deserialization of ArrayList:

try {
FileInputStream fileInputStream = new FileInputStream("data");
ObjectInputStream objectInputStream
= new ObjectInputStream(fileInputStream);

   ArrayList<String> arrayList 
            = (ArrayList<String>) objectInputStream.readObject();
   System.out.println(arrayList);

   fileInputStream.close();
   objectInputStream.close();
Enter fullscreen mode Exit fullscreen mode

} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}

To learn in details, visit: https://www.java8net.com/2020/03/serialize-arraylist-in-java.html

Further Readings:
https://www.java8net.com/2020/03/synchronized-arraylist-in-java.html
https://www.java8net.com/2020/02/how-to-sort-arraylist-in-java.html
https://www.java8net.com/2020/03/initialize-arraylist-in-java.html
https://www.java8net.com/2020/03/arraylist-to-hashmap-in-java.html

Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil — patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay