HashMap可序列化

jav*_*eek 32 java serialization hashmap

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

Thi*_*ilo 37

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

/**
  * 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());
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

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

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

  • @PeterWippermann:你确定吗?这个`loadFactor`不是瞬态的,它应该包含在`defaultWriteObject`生成的输出中.(实际上,在调用defaultWriteObject之前,源代码中的注释直接提到了这一点). (3认同)
  • 哦,你当然是对的!我没有注意到它会受到默认序列化的影响.谢谢你指点我!:-) (2认同)

Ron*_*erg 9

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