问题
Why is the table
field of Hashtable
serialized, although it is marked as transient
?
回答1:
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.
回答2:
Because 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".
回答3:
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.
来源:https://stackoverflow.com/questions/2524140/why-is-the-table-attribute-of-hashtable-serialized