ArrayList中为什么使用transient修饰elementData?
2017-07-20 18:03
295 查看
为什么使用transient修饰elementData?
既然要将ArrayList的字段序列化(即将elementData序列化),那为什么又要用transient修饰elementData呢?回想ArrayList的自动扩容机制,elementData数组相当于容器,当容器不足时就会再扩充容量,但是容器的容量往往都是大于或者等于ArrayList所存元素的个数。
比如,现在实际有了8个元素,那么elementData数组的容量可能是8x1.5=12,如果直接序列化elementData数组,那么就会浪费4个元素的空间,特别是当元素个数非常多时,这种浪费是非常不合算的。
所以ArrayList的设计者将elementData设计为transient,然后在writeObject方法中手动将其序列化,并且只序列化了实际存储的那些元素,而不是整个数组。
见源码:
// Write out all elements in the proper order. for (int i=0; i<size; i++) { s.writeObject(elementData[i]); }
从源码中,可以观察到 循环时是使用i<size而不是 i<elementData.length,说明序列化时,只需实际存储的那些元素,而不是整个数组。
相关文章推荐
- ArrayList的elementData为什么要用transient修饰
- ArrayList的elementData为什么要修饰为transient?
- Arraylist的elementData修饰关键词transient到底要闹哪样
- ArrayList的elementData声明为transient,为什么还可以序列化
- 序列化与ArrayList 的elementData的修饰关键字transient
- java的ArrayList中,数组为什么被transient修饰,这是因为什么原因而设计出来的?
- 用transient修饰的成员变量不能序列化,为什么ArrayList集合可以实现序列化
- ArrayList中elementData为什么被transient修饰?
- ArrayList中的数组为什么被transient修饰
- java中ArrayList中为什么elementData使用了transient
- 为什么局部字符数组必须使用static关键词修饰
- WP01 – 为什么实现Multi-Tier, 为什么使用 Data Abstract?
- 局部内部类访问外部变量为什么需要使用final修饰
- tips:为什么接口中的常量必须使用public static final修饰?
- 使用外部类变量时为什么需要final修饰【转】
- 为什么我们使用List list =new ArrayList();而不用ArrayList list = new ArrayList();
- 使用HTML5中的element.dataset操作自定义data-*数据
- 为什么 FleaPHP 使用 Table Data Gateway 代替 Active Record 来提供数据库访问服务
- 为什么 FleaPHP 使用 Table Data Gateway 代替 Active Record 来提供数据库访问服务
- Java 有几程方法可以实现一个线程?用什么关键字修饰同步?stop()和suspend()为什么不推荐使用?