Confusion of HashMap Keyword transient in Java

  java, question

There are objects transient [] table in HashMap; This is where the data is stored, but why add the keyword transient?

Interpretation of transient
Transient is a Java language keyword used to indicate that a domain is not part of the serialization of the object. When an object is serialized, the value of the transient variable is not included in the serialized representation, that is, it cannot be persisted.

So why is this design used in HashMap? What’s the point?

Good question. Of course, the reasons are as follows@WindozeIt is said that there are efficient considerations, but there are deeper reasons.

Effective Java 2nd, Item75, Joshua mentioned:

For example, consider the case of a hash table. The physical
representation is a sequence of hash buckets containing key-value
entries. The bucket that an entry resides in is a function of the hash
code of its key, which is not, in general, guaranteed to be the same
from JVM implementation to JVM implementation. In fact, it isn’t even
guaranteed to be the same from run to run. Therefore,accepting the
default serialized form for a hash table would constitute a serious
BUGS. Serializing and deserializing the hash table could yield an
object whose invariants were seriously corrupt.

How do you understand? Look at HashMap.get()/put (). Read/write Map is based on Object.hashcode () to determine which bucket to read/write from. Object.hashcode () is a native method, and different JVM inside may be different.

For example, to store an entry to HashMap, the key is the STRING “STRING”, in the first java program inside, the hashcode () of “string” is 1, and it is stored in bucket number 1; In the second java program inside, hashcode () of “STRING” may be 2 and stored in bucket No.2. If the default serialization is used (Entry[] table does not use transient), then this HashMap will import the second java program from the first java program inside through serialization. The memory distribution is the same. This is wrong. HashMap’s current readObject and writeObject output/input content and regenerate HashMap.