为什么HashMap的哈希表被标记为transient,尽管类是可序列化的

发布于 2025-01-02 11:53:48 字数 346 浏览 1 评论 0 原文

我正在查看 HashMap 的来源。

HashMap 实现可序列化

好的,这样它就可以作为对象保存/传输。

但我看到哈希表本身被标记为transient

我不明白这一点。如果您将其标记为瞬态,这是否意味着它不应该被序列化?

但所有数据都在表中。那为什么会瞬态呢?

也许我对 Serialized 的工作原理感到困惑?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

强辩 2025-01-09 11:53:49

HashMap 使用 writeObjectreadObject 来实现自定义序列化,而不是仅仅让其字段正常序列化。它将存储桶的数量、总大小和每个条目写入流中,并在反序列化时从这些字段重建自身。正如 tzaman 所说,表本身在串行形式中是不必要的,因此它不会被序列化以节省空间。

您可以在 writeReplace 和 readResolve) /javase/6/docs/api/java/io/Serializing.html">可序列化 javadoc。

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.

幸福%小乖 2025-01-09 11:53:49

transient 关键字指示字段不应包含在类的序列化表示中。 HashMapEntry[] 表只是一个加速结构 - 它允许快速查找存储的条目。
整个表本身不需要序列化,只需序列化它包含的条目,因为从条目列表反序列化时可以再次重建表。

The transient keyword indicates that a field shouldn't be included in the serialized representation of a class. The Entry[] table of a HashMap is simply an acceleration structure - it allows for fast lookup of the stored entries.
The entire table itself doesn't need to be serialized, just the entries it contains, since the table can be rebuilt again when deserializing from the list of entries.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文