Why is the table
field of Hashtable
serialized, although it is marked as transient
?
views:
69answers:
3Because it has writeObject()
and readObject()
implemented (in private methods), with which it can control how it is to be serialized and deserialized. It's around line 800 in Java 1.6 source code.
Check this Sun advanced serialization guide for details how it works "under the hoods".
If you look at the source code of the Hashtable class (at least in 1.6), the Entry[] table
is marked as transient
but the class implements writeObject()
, in which it writes the contents of the entry table to the ObjectOutputStream
.
Thus the contents of the Hashtable are always serialized.
Why did they choose to implement it this way? Likely to have control over how the array is serialized.
It is marked as transient because it is unsafe to use the default serialization scheme on the Entry array. Rather, when a Hashtable is deserialized, the keys in the table must be rehashed and the entries must be added to slots according to the new hashcode values. This is necessary because the keys may have different hashcodes after deserialization ... for a variety of reasons. This work will be done by Hashtable's readObject()
method.