HashMap实现了Serialized接口;所以可以序列化。我查看了 HashMap 的实现,并且 Entry[] 表被标记为瞬态。由于Entry[]表是存储Map全部内容的表,如果不能序列化,那么反序列化时Map是如何构造回来的
如果你看来源 http://www.docjar.com/html/api/java/util/HashMap.java.html您将看到它不依赖于默认的序列化机制,而是手动写出所有条目(作为键和值的交替流):
/**
* Save the state of the <tt>HashMap</tt> instance to a stream (i.e.,
* serialize it)
*
* @serialData The <i>capacity</i> of the HashMap (the length of the
* bucket array) is emitted (int), followed by the
* <i>size</i> (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<Map.Entry<K,V>> 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<K,V> e = i.next();
s.writeObject(e.getKey());
s.writeObject(e.getValue());
}
}
}
这比数组更紧凑,数组可以包含许多空条目和链接链以及 Map$Entry 包装器的开销。
请注意,它仍然调用defaultWriteObject
对于“简单”字段。为了使其发挥作用,它必须将其他所有内容标记为transient
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)