java list序列化

编图书馆的时候用了很多ArrayList,发现了反序列化后出现了如下问题:序列化前两个ArrayList中的某一元素指向同一对象,经过序列化再反序列化过程后,他们居然指向了不同对象,出现了不同步的问题,那是为什么呢?

查看一下Java.util里面的ArrayList源代码,发现ArrayList 重写了writeObject方法和readObject方法:

/**

* Save the state of the <tt>ArrayList</tt> instance to a stream (that

* is, serialize it).

*

*@serialDataThe length of the array backing the <tt>ArrayList</tt>

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

* (each an <tt>Object</tt>) in the proper order.

*/

privatevoidwriteObject(java.io.ObjectOutputStream s)

throwsjava.io.IOException{

// Write out element count, and any hidden stuff

intexpectedModCount = modCount;

s.defaultWriteObject();

// Write out array length

s.writeInt(elementData.length);

// Write out all elements in the proper order.

for(inti=0; i<size; i++)

s.writeObject(elementData[i]);

if(modCount != expectedModCount) {

thrownewConcurrentModificationException();

}

}

/**

* Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,

* deserialize it).

*/

privatevoidreadObject(java.io.ObjectInputStream s)

throwsjava.io.IOException, ClassNotFoundException {

// Read in size, and any hidden stuff

s.defaultReadObject();

// Read in array length and allocate array

intarrayLength = s.readInt();

Object[] a = elementData =newObject[arrayLength];

// Read in all elements in the proper order.

for(inti=0; i<size; i++)

a[i] = s.readObject();

}

经过分析源代码以及实践证明:像Arraylist之类的引用序列化仍然是有效的,但是序列化之前ArrayList中指向同一对象的引用经过序列化和反序列化之后,这个关系将被破坏,即他们不再指向同一个对象,而是指向了两个不同的对象。原因在于序列化的时候是直接把Arraylist中每个元素指向的对象写到文件中,反序列化时再一一读出。这点值得大家在编程的时候注意。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值