Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 264
abo Avatar asked Sep 09 '26 20:09

abo


1 Answers

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.

like image 122
Sergey Kalinichenko Avatar answered Sep 12 '26 09:09

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!