Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Serialize a list in java?

I would like to deep clone a List. for that we are having a method

// apache commons method. This object should be serializable SerializationUtils.clone ( object )  

so now to clone my List i should convert that to serializable first. Is it possible to convert a List into Serializable list?

like image 375
Rakesh Juyal Avatar asked Sep 07 '09 07:09

Rakesh Juyal


People also ask

Can you serialize a list 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.

Can lists be serialized?

A List can be serialized—here we serialize (to a file) a List of objects. Serialize notes. The next time the program runs, we get this List straight from the disk. We see an example of BinaryFormatter and its Serialize methods.


1 Answers

All standard implementations of java.util.List already implement java.io.Serializable.

So even though java.util.List itself is not a subtype of java.io.Serializable, it should be safe to cast the list to Serializable, as long as you know it's one of the standard implementations like ArrayList or LinkedList.

If you're not sure, then copy the list first (using something like new ArrayList(myList)), then you know it's serializable.

like image 196
skaffman Avatar answered Sep 20 '22 07:09

skaffman