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?
Hashmap: A HashMap stores items in key/value pairs, and we can access them by an index of another type (such as a string). Now to serialize anything, you have to implement the java. io. Serializable interface and HashMap also implements the Serializable interface.
Transient in Java is used to mark the member variable not to be serialized when it is persisted to streams of bytes. This keyword plays an important role to meet security constraints in Java. It ignores the original value of a variable and saves the default value of that variable data type.
When we mark any variable as transient, then that variable is not serialized. Since transient fields aren't present in the serialized form of an object, the deserialization process would use the default values for such fields when creating an object out of the serialized form.
HashMap takes care of its own serialization through the use of the writeObject and readObject methods. Show activity on this post. HashMaps don't serialize their Entry objects during serialization.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With