I was looking at the source of HashMap.
A HashMap
implements Serializable
.
Ok this is so that it can be peristed/transmitted as
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.
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.