Why are variable member variables widely used in the standard Java library?

After looking at the source code for some of the Java Collection classes, I found that member variables always change with transient.

For example, the source code LinkedList:

public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
    private transient Entry<E> header = new Entry<E>(null, null, null);
    private transient int size = 0;

    public LinkedList() 
    {
        header.next = header.previous = header;
    }

    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }

    // ...other stuff
}

Of course, not only does it LinkedListuse the transient, almost all Java collection classes use transientat least half of their member variables to change.

So my question is: why transientused so widely in the standard Java library?

(Of course, everyone knows the definition and use transient, but this is not my question :)

+6
source share
2

.

, - ,

LinkedList . , , , . .

, size, , Node<E> . size. , LinkedList size. , entries, , .

, , .

@SuppressWarnings("unchecked")
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());
}

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++;
}
+7

( , POJO), , .

- transient readObject()/writeObject(), , , transient .

- , , readResolve()/writeReplace(). ( EnumSet.)

, , . , , API, API API, , , , . ( API Swing, Javadocs .)

, . (, , - , , .)

+1

Source: https://habr.com/ru/post/1615378/


All Articles