如何在java中序列化列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1387954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:31:05  来源:igfitidea点击:

How to Serialize a list in java?

javaserializationcollectionsapache-commons

提问by Rakesh Juyal

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?

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

采纳答案by skaffman

All standard implementations of java.util.Listalready implement java.io.Serializable.

java.util.List已经实现的所有标准实现java.io.Serializable

So even though java.util.Listitself 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 ArrayListor LinkedList.

因此,即使它java.util.List本身不是 的子类型java.io.Serializable,也应该安全地将列表转换为Serializable,只要您知道它是标准实现之一,例如ArrayListor LinkedList

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

如果您不确定,请先复制列表(使用类似new ArrayList(myList)),然后您就知道它是可序列化的。

回答by Dirk

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

List只是一个接口。问题是:您的实际List实现是可序列化的吗?谈到Java 运行时的标准List实现(ArrayListLinkedList),它们中的大多数实际上已经是了。

回答by Brian Agnew

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

正如已经指出的,大多数标准实现List都是可序列化的。但是,您必须确保列表中引用/包含的对象也是可序列化的。