gpt4 book ai didi

java - 为什么CopyOnWriteArrayList需要自定义序列化

转载 作者:行者123 更新时间:2023-11-30 07:13:22 24 4
gpt4 key购买 nike

我阅读了CopyOnWriteArrayList(JDK 1.8)的源代码,发现它实现了writeObject和readObject。我的问题是为什么CopyOnWriteArrayList需要自定义序列化?

   /**
* Saves this list to a stream (that is, serializes it).
*
* @param s the stream
* @throws java.io.IOException if an I/O error occurs
* @serialData The length of the array backing the list 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 {

s.defaultWriteObject();

Object[] elements = getArray();
// Write out array length
s.writeInt(elements.length);

// Write out all elements in the proper order.
for (Object element : elements)
s.writeObject(element);
}

/**
* Reconstitutes this list from a stream (that is, deserializes it).
* @param s the stream
* @throws ClassNotFoundException if the class of a serialized object
* could not be found
* @throws java.io.IOException if an I/O error occurs
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {

s.defaultReadObject();

// bind to new lock
resetLock();

// Read in array length and allocate array
int len = s.readInt();
Object[] elements = new Object[len];

// Read in all elements in the proper order.
for (int i = 0; i < len; i++)
elements[i] = s.readObject();
setArray(elements);
}

谢谢。

最佳答案

我已经得到答案了。如果我们使用默认的序列化,可能会序列化许多空元素。

关于java - 为什么CopyOnWriteArrayList需要自定义序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38805913/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com