This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.
// Read capacity and verify non-negative. intcapacity= s.readInt(); if (capacity < 0) { thrownewInvalidObjectException("Illegal capacity: " + capacity); }
// Read load factor and verify positive and non NaN. floatloadFactor= s.readFloat(); if (loadFactor <= 0 || Float.isNaN(loadFactor)) { thrownewInvalidObjectException("Illegal load factor: " + loadFactor); } // Clamp load factor to range of 0.25...4.0. loadFactor = Math.min(Math.max(0.25f, loadFactor), 4.0f);
// Read size and verify non-negative. intsize= s.readInt(); if (size < 0) { thrownewInvalidObjectException("Illegal size: " + size); } // Set the capacity according to the size and load factor ensuring that // the HashMap is at least 25% full but clamping to maximum capacity. capacity = (int) Math.min(size * Math.min(1 / loadFactor, 4.0f), HashMap.MAXIMUM_CAPACITY);
// Constructing the backing map will lazily create an array when the first element is // added, so check it before construction. Call HashMap.tableSizeFor to compute the // actual allocation size. Check Map.Entry[].class since it's the nearest public type to // what is actually created.
// Read in all elements in the proper order. for (int i=0; i<size; i++) { @SuppressWarnings("unchecked") Ee= (E) s.readObject(); map.put(e, PRESENT); } }
最后的for循环调用了map的put函数
尽管在HashSet对使用transient修饰map
1
privatetransient HashMap<E,Object> map;
但是在序列化过程中,会逐一读取map中的元素并把元素写入流中
HashSet中的writeObject函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
privatevoidwriteObject(java.io.ObjectOutputStream s) throws java.io.IOException { // Write out any hidden serialization magic s.defaultWriteObject();
// Write out HashMap capacity and load factor s.writeInt(map.capacity()); s.writeFloat(map.loadFactor());
// Write out size s.writeInt(map.size());
// Write out all elements in the proper order. for (E e : map.keySet()) s.writeObject(e); }