Why is the table attribute of Hashtable serialized?

余生长醉 提交于 2019-12-10 18:06:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!