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的哈希表标


基础教程推荐
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01