Why is the hash table of HashMap marked as transient although the class is serializable

26,487

Solution 1

HashMap uses writeObject and readObject to implement custom serialization rather than just letting its field be serialized normally. It writes the number of buckets, the total size and each of the entries to the stream and rebuilds itself from those fields when deserialized. As tzaman says, the table itself is unnecessary in the serial form, so it's not serialized to save space.

You can read more about those methods and some other methods of doing custom serialization (writeReplace and readResolve) in the Serializable javadoc.

Solution 2

The transient keyword indicates that a field shouldn't be included in the serialized representation of a class. The Entry[] table of a HashMap is simply an acceleration structure - it allows for fast lookup of the stored entries. The entire table itself doesn't need to be serialized, just the entries it contains, since the table can be rebuilt again when deserializing from the list of entries.

Share:
26,487
Cratylus
Author by

Cratylus

Updated on July 09, 2022

Comments

  • Cratylus
    Cratylus almost 2 years

    I was looking at the source of HashMap.

    A HashMap implements Serializable.

    Ok this is so that it can be peristed/transmitted as an object.

    But I see that the hashtable itself is marked as transient.

    I don't get this.If you mark it as transient, doesn't this mean that it should not be serialized?

    But all the data are in the table.So why is it transient?

    Perhaps I am confused on how Serializable works?