简体   繁体   English

为什么ArrayList实现Serializable?

[英]Why does ArrayList implement Serializable?

I tried to serialize an ArrayList with JAXB and failed. 我试图用JAXB序列化ArrayList并失败。 Is this because elementData is marked as transient? 这是因为elementData被标记为瞬态?

Why does the ArrayList implement the Serializable Inferface and has it's data transient? 为什么ArrayList实现Serializable Inferface并且它的数据是瞬态的?

I try to serialize an ArrayList of Serializables: 我尝试序列化Serializables的ArrayList:

JAXBElement<ArrayList> jaxbElement = new JAXBElement<ArrayList>(new QName(ArrayList.class.getSimpleName()), ArrayList.class, allEntities);
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(jaxbElement, System.out);

How to do this via JAXB? 如何通过JAXB执行此操作?

ArrayList implements Serializable, so it can be serialized, that's exactly why the private backing array is transient, so it is not serialized along with other data in the class, since all is handled by ArrayList's writeObject and readObject methods. ArrayList实现Serializable,因此它可以被序列化,这正是私有后备数组是瞬态的原因,因此它不与类中的其他数据一起序列化,因为所有数据都由ArrayList的writeObject和readObject方法处理。

It does this because it provides custom readObject and writeObject methods that do a better job of serialization than the default. 这样做是因为它提供了自定义的readObject和writeObject方法,这些方法比默认方法更好地进行序列化。 Specifically, the writeObject method writes just the size and the sequence of elements. 具体来说,writeObject方法只写入元素的大小和顺序。 This avoids serializing the private array object which 1) has its own header and overheads, and 2) is typically padded with nulls. 这避免了序列化私有数组对象,其中1)具有其自己的头和开销,并且2)通常用空值填充。 The space saving can be significant. 节省空间可能很重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM