Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 912
Cratylus Avatar asked Feb 04 '12 20:02

Cratylus


People also ask

What if HashMap contains serializable objects?

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.

What is the purpose of transient keyword in serialization?

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.

Why are transient variables not serialized?

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.

Is HashMap serialized?

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.


1 Answers

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.

like image 67
ColinD Avatar answered Sep 24 '22 14:09

ColinD