abo
abo

Reputation: 378

How arraylist perserve data after serialization

When checking java.util.ArrayList implementation notice that element data object array in side the arrayList is transient even though ArrayList is serializable.

transient Object[] elementData; // non-private to simplify nested class access

So how does arrayList preserve its data in deserialization process by keeping elementData array transient?

Upvotes: 3

Views: 147

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

Marking a member transient does not mean the field is not getting serialized, only that it is not serialized automatically using Java's built-in serialization mechanism for fields.

In case of ArrayList serialization is performed by a custom writeObject method: [src]

private void writeObject(java.io.ObjectOutputStream s)
    throws java.io.IOException {
    // Write out element count, and any hidden stuff
    int expectedModCount = modCount;
    s.defaultWriteObject();
    // Write out size as capacity for behavioural compatibility with clone()
    s.writeInt(size);
    // Write out all elements in the proper order.
    for (int i=0; i<size; i++) {
        s.writeObject(elementData[i]);
    }
    if (modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }
}

Deserialization is performed using readObject.

Upvotes: 4

Related Questions