Làm thế nào để Serialize một danh sách trong java?


81

Tôi muốn sao chép sâu một Danh sách. vì chúng tôi đang có một phương pháp

// 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?

Câu trả lời:


162

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.


1
Why would anyone ever want to cast anything to Serializable? Serializable is only a marker interface; casting something to Serializable isn't useful.
Jesper

19
Because SerializationUtils.clone() requires an argument on type Serializable, and so if your variable is of type List, you'll need to cast it.
skaffman

2
@Jesper: It's a marker interface that says it's safe to serialize the class. Android uses the Serializable interface for many things; passing along intent extras, shared preferences, etc.
Zack Marrapese

11
Yes, I found this question when searching Android solutions. My addition is, List<MyClass> myObjs = new ArrayList<MyClass>(); doesn't meet the Serializable, but ArrayList<MyClass> myObjs = new ArrayList<MyClass>(); does.
Evi Song

2
@Adam It might be best to guarantee safety at compile-time instead by using the signature <T extends List<Foo> & Serializable> setFooList(T list), which requires your caller to pass you an instance of some List implementation that is also Serializable.
Theodore Murdock

32

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.


1
As pointed out already, List is an interface that does not extend Serializable or any interface that does so. Lists that are not serializable may not be common in standard libraries, but that does not make the first sentence right.
arne.b

13

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.

Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.