javaarraylisttransient

Why does ArrayList use transient storage?


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

private transient Object[] elementData;

Why does this need to be transient? Why can't this class be serialized?

Thanks for the help!


Solution

  • 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().