java elementdata_[ Java ]ArrayList 里面 elementData 为什么要设成 transient

看了下 ArrayList 的源码

/**

* The array buffer into which the elements of the ArrayList are stored.

* The capacity of the ArrayList is the length of this array buffer. Any

* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA

* will be expanded to DEFAULT_CAPACITY when the first element is added.

*/

transient Object[] elementData; // non-private to simplify nested class access

看到 elementData 是 transient 的,于是又去看了下序列化的实现。

/**

* Save the state of the ArrayList instance to a stream (that

* is, serialize it).

*

* @serialData The length of the array backing the ArrayList

* instance is emitted (int), followed by all of its elements

* (each an Object) in the proper order.

*/

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

s.writeObject(elementData[i]);

}

if (modCount != expectedModCount) {

throw new ConcurrentModificationException();

}

}

我觉得这里没有必要把 elementData 设成 transient,然后再一个一个遍历输出。直接用 defaultWriteObject 把 elementData 输出就可以了。

我自己写了个 Dummy 的 ArrayList 测试,是可以直接序列化+反序列化数组的。

求大神指点。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值