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

标签 java

我阅读了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/

相关文章:

java - 如何获取对应于notes、totalqtypctmin、totalqtypctmax、mismatchthresholdpct、prodgrp、prodid、locgroup、geoid的给定xml文件的数据?

java - Android - 自定义 View - 使用顶部 View 扩展 EditText

java - 从图库中选择一张图片并将其显示在另一个 Activity 中

java - SVG 到 Java Graphics2D

java - 坚持尝试将随机对象用于我的 Java 计算机编程入门作业

java - ThreadLocal 垃圾回收

java - 设置特定 JFrame 的分辨率,而不是计算机的分辨率

java - WildFly jdbc 与 Oracle 的连接

java - 将一条线分成两个不同的对象

java - 如何设置具有安全约束的 Faces Servlet 映射