Why is the hash table of HashMap marked as transient although the class is serializable(为什么尽管类是可序列化的,但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
使用 writeObject
和 readObject
来实现自定义序列化,而不仅仅是让它的字段正常序列化.它将桶的数量、总大小和每个条目写入流,并在反序列化时从这些字段中重建自身.正如 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的哈希表标记为瞬态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么尽管类是可序列化的,但HashMap的哈希表标


- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01