Why does ArrayList use transient storage?

前端 未结 6 1159
既然无缘
既然无缘 2020-12-24 05:55

I was reading the source of Java\'s ArrayList and I came across its backing array declaration:

private transient Object[] elementData;

Why

6条回答
  •  有刺的猬
    2020-12-24 06:37

    It can be serialized; the ArrayList class just takes care of things itself, rather than using the default mechanism. Look at the writeObject() and readObject() methods in that class, which are part of the standard serialization mechanism.

    If you look at the source, you see that writeObject() does not save the backing array. Instead, it serializes the elements (including null values) one at a time up to the size() limit. This avoids the overheads of serializing the array, and especially any unused slots at the end of the array. On deserialization, a new backing array of the minimum required size is created by readObject().

提交回复
热议问题