为什么尽管类是可序列化的,但HashMap的哈希表标记为瞬态 [英] Why is the hash table of HashMap marked as transient although the class is serializable

查看:19
本文介绍了为什么尽管类是可序列化的,但HashMap的哈希表标记为瞬态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看 HashMap 的来源.

I was looking at the source of HashMap.

一个HashMap 实现可序列化.

好的,这样它就可以作为一个对象被持久化/传输.

Ok this is so that it can be peristed/transmitted as an object.

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

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?

但是所有的数据都在表中.那为什么是transient呢?

But all the data are in the table.So why is it transient?

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

Perhaps I am confused on how Serializable works?

推荐答案

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

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.

您可以在 Serializable javadoc.

You can read more about those methods and some other methods of doing custom serialization (writeReplace and readResolve) in the Serializable javadoc.

这篇关于为什么尽管类是可序列化的,但HashMap的哈希表标记为瞬态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆