HashMap可序列化

HashMap实现了Serializable接口; 所以它可以序列化。 我查看了HashMap的实现,并将Entry []表标记为瞬态。 由于Entry []表是存储Map的全部内容的表,如果无法序列​​化,那么在反序列化过程中如何构造Map?

如果查看源代码,您将看到它不依赖于默认的序列化机制,而是手动写出所有条目(作为键和值的交替流):

/** * Save the state of the HashMap instance to a stream (ie, * serialize it) * * @serialData The capacity of the HashMap (the length of the * bucket array) is emitted (int), followed by the * size (an int, the number of key-value * mappings), followed by the key (Object) and value (Object) * for each key-value mapping. The key-value mappings are * emitted in no particular order. */ private void writeObject(java.io.ObjectOutputStream s) throws IOException { Iterator> i = (size > 0) ? entrySet0().iterator() : null; // Write out the threshold, loadfactor, and any hidden stuff s.defaultWriteObject(); // Write out number of buckets s.writeInt(table.length); // Write out size (number of Mappings) s.writeInt(size); // Write out keys and values (alternating) if (i != null) { while (i.hasNext()) { Map.Entry e = i.next(); s.writeObject(e.getKey()); s.writeObject(e.getValue()); } } } 

这比数组更紧凑,数组可以包含许多空条目和链接链以及Map $ Entry包装器的开销。

请注意,它仍然为“简单”字段调用defaultWriteObject 。 为了使其工作,它必须将其他所有内容标记为transient

HashMap通过使用writeObjectreadObject方法来处理自己的序列化。

HashMaps在序列化期间不会序列化其Entry对象。 看一下它的writeObject方法。

javadoc解释:

HashMap的容量(桶数组的长度)发出(int),后跟size(一个int,键值映射的数量),然后是每个键的键(Object)和值(Object)键值映射。 键值映射不按特定顺序发出。

如果查看readObject方法,您将看到如何使用大小,键和值重建Entry表。