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

原文链接:How to serialize and deserialize ArrayList in Java

© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容