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

前端 未结 2 539
悲&欢浪女
悲&欢浪女 2020-12-15 04:46

I was looking at the source of HashMap.

A HashMap implements Serializable.

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

相关标签:
2条回答
  • 2020-12-15 05:11

    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.

    0 讨论(0)
  • 2020-12-15 05:18

    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.

    0 讨论(0)
提交回复
热议问题