前端开发入门到精通的在线学习网站

网站首页 > 资源文章 正文

为什么 ArrayList 的 elementData 加上 transient 修饰?

qiguaw 2024-11-23 21:18:28 资源文章 11 ℃ 0 评论

在日常开发中经常会用到ArrayList,平时有没有对ArrayList源码进行过研究呢?

今天说一下elementData为什么用transient 修饰。来看源码


其实也很好解释,ArrayList 实现了 Serializable 接口,这意味着 ArrayList 支持序列化,

transient 的作用是说不希望 elementData 数组被序列化,重写了 writeObject 实现:

private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOE xception{ 
  // Write out element count, and any hidden stuff* 
  int 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();
}

每次序列化时,先调用 defaultWriteObject() 方法序列化 ArrayList 中的非transient 元素,然后遍历 elementData,只序列化已存入的元素,这样既加快了序列化的速度,又减小了序列化之后的文件大小。


高端面试题分享,如果对您有帮助,请关注我!

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表