如何在 Java 中序列化列表?

我想深入克隆一个名单。为此,我们有一个方法

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

所以现在要克隆我的 List 我应该先把它转换成序列化的。是否可以将列表转换为可序列化列表?

186428 次浏览

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.

List is just an interface. The question is: is your actual List implementation serializable? Speaking about the standard List implementations (ArrayList, LinkedList) from the Java run-time, most of them actually are already.

As pointed out already, most standard implementations of List are serializable. However you have to ensure that the objects referenced/contained within the list are also serializable.