ArrayList的elementData为什么要修饰为transient?

来源:互联网 发布:删除数据库 编辑:程序博客网 时间:2024/04/28 01:11

ArrayList源码:

private transient Object[] elementData;
为什么要将elementData修饰为transient呢?
比较靠谱的说法:
elementData数组相当于容器,当容器不足时就会再扩充容量,但是容器的容量往往都是大于或者等于ArrayList所存元素的个数。
比如,现在实际有了8个元素,那么elementData数组的容量可能是8x1.5=12,如果直接序列化elementData数组,那么就会浪费4个元素的空间,特别是当元素个数非常多时,这种浪费是非常不合算的。所以ArrayList的设计者将elementData设计为transient,然后在writeObject方法中手动将其序列化,并且只序列化了实际存储的那些元素,而不是整个数组。

ArrayList覆写的writeObject()方法代码:
private void writeObject(java.io.ObjectOutputStream s)        throws java.io.IOException{// Write out element count, and any hidden stuffint expectedModCount = modCount;s.defaultWriteObject();        // Write out array length        s.writeInt(elementData.length);// 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();        }    }

可观察到循环时是使用i<size而不是i<elementData.length说明序列化时,只需实际存储的那些元素,而不是整个数组。

参考地址:http://www.cnblogs.com/aoguren/p/4767309.html

0 0
原创粉丝点击