Why does ArrayList use transient storage?

前端 未结 6 1306
既然无缘
既然无缘 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:39

    Extending on Stephen C's answer above, I would like to correct his note about transient being used, in ArrayLists's case, for readability. This may be better as a comment under his answer but I don't have that ability yet!

    While the field being marked as transient is helpful for readability, it is also necessary due to the custom readObject and writeObject methods calling java.io.ObjectInputStream's defaultReadObject and java.io.ObjectOutputStream's defaultWriteObject methods respectively. These methods will do the dirty work of handling serializiation of all the fields not marked transient (e.g. size).

    See the source code for ObjectOutputStream for more details here: https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/share/classes/java/io/ObjectOutputStream.java#L431

提交回复
热议问题