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

Why is the hash table of HashMap marked as transient although the class is serializable(为什么尽管类是可序列化的,但HashMap的哈希表标记为瞬态)
本文介绍了为什么尽管类是可序列化的,但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的哈希表标记为瞬态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How can create a producer using Spring Cloud Kafka Stream 3.1(如何使用Spring Cloud Kafka Stream 3.1创建制片人)
Insert a position in a linked list Java(在链接列表中插入位置Java)
Did I write this constructor properly?(我是否正确地编写了这个构造函数?)
Head value set to null but tail value still gets displayed(Head值设置为空,但仍显示Tail值)
printing nodes from a singly-linked list(打印单链接列表中的节点)
Control namespace prefixes in web services?(控制Web服务中的命名空间前缀?)