一尘不染

HashMap可序列化

java

HashMap实现了Serializable接口;因此可以序列化。我已经看过HashMap的实现,Entry []表被标记为瞬态。由于Entry
[]表是存储Map的全部内容的表,如果无法序列​​化,则在反序列化期间如何构造Map


阅读 476

收藏
2020-12-03

共1个答案

一尘不染

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

/**
  * 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为“ easy”字段调用。为了使其正常工作,它必须将其他所有内容都标记为transient

2020-12-03