Search code examples
javaserializationlinked-listtransient

How serialization work in LinkedList?


I don't understand how LinkedList understand's where the first and last element is after deserialization. Because fields have the following structure

/**
 * Pointer to first node.
 * Invariant: (first == null && last == null) ||
 *            (first.prev == null && first.item != null)
 */
transient Node<E> first;

/**
 * Pointer to last node.
 * Invariant: (first == null && last == null) ||
 *            (last.next == null && last.item != null)
 */
transient Node<E> last;

Can anyone help understand it?


Solution

  • The LinkedList method readObject determines what first and last refer to during the reconstruction of the list. Here's the code from the link:

    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        // Read in any hidden serialization magic
        s.defaultReadObject();
    
        // Read in size
        int size = s.readInt();
    
        // Read in all elements in the proper order.
        for (int i = 0; i < size; i++)
            linkLast((E)s.readObject());
    }
    

    The linkLast method keeps track of first and last. It initializes first and last on the first node to be reconstructed and it updates last with each newly reconstructed node.

    void linkLast(E e) {
        final Node<E> l = last;
        final Node<E> newNode = new Node<>(l, e, null);
        last = newNode;
        if (l == null)
            first = newNode;
        else
            l.next = newNode;
        size++;
        modCount++;
    }