ArrayList中elementData为什么使用transient关键字修饰呢?
下文笔者讲述Arraylist源码中的elementData使用transient关键字修饰的缘由说明,如下所示
ArrayList重写了writeObject方法
writeObject()方法是每次序列化时调用的方法
ArrayList源码定义
private transient Object[] elementData; 我们知道使用transient关键字修饰后 在数组序列化时,不会将elementData字段序列化 那是因为ArrayList在序列化时,会调用writeObject方法 只序列化已存入的元素,这样可减少序列化后的体积 也提高了运行效率例:
ArrayList重写了writeObject方法
writeObject()方法是每次序列化时调用的方法
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
// Write out element count, and any hidden stuff
int expectedModCount = modCount;
s.defaultWriteObject();
// Write out size as capacity for behavioural compatibility with clone()
s.writeInt(size);
// Write out all elements in the proper order.
for (int i=0; i<size; i++) {
s.writeObject(elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


