privatevoidwriteObject(java.io.ObjectOutputStream s)throwsIOException{int buckets =capacity();// Write out the threshold, loadfactor, and any hidden stuff
s.defaultWriteObject();
s.writeInt(buckets);//写入初始容量大小
s.writeInt(size);//写入hashmap节点的数量internalWriteEntries(s);}
反序列化
privatevoidreadObject(java.io.ObjectInputStream s)throwsIOException,ClassNotFoundException{// Read in the threshold (ignored), loadfactor, and any hidden stuff
s.defaultReadObject();reinitialize();//初始化if(loadFactor <=0||Float.isNaN(loadFactor))thrownewInvalidObjectException("Illegal load factor: "+
loadFactor);
s.readInt();// Read and ignore number of bucketsint mappings = s.readInt();// Read number of mappings (size)if(mappings <0)thrownewInvalidObjectException("Illegal mappings count: "+
mappings);elseif(mappings >0){// (if zero, use defaults)// Size the table using given load factor only if within// range of 0.25...4.0float lf =Math.min(Math.max(0.25f, loadFactor),4.0f);float fc =(float)mappings / lf +1.0f;int cap =((fc < DEFAULT_INITIAL_CAPACITY)?
DEFAULT_INITIAL_CAPACITY :(fc >= MAXIMUM_CAPACITY)?
MAXIMUM_CAPACITY :tableSizeFor((int)fc));float ft =(float)cap * lf;
threshold =((cap < MAXIMUM_CAPACITY && ft < MAXIMUM_CAPACITY)?(int)ft :Integer.MAX_VALUE);// Check Map.Entry[].class since it's the nearest public type to// what we're actually creating.SharedSecrets.getJavaOISAccess().checkArray(s,Map.Entry[].class, cap);@SuppressWarnings({"rawtypes","unchecked"})Node<K,V>[] tab =(Node<K,V>[])newNode[cap];
table = tab;// Read the keys and values, and put the mappings in the HashMapfor(int i =0; i < mappings; i++){@SuppressWarnings("unchecked")K key =(K) s.readObject();@SuppressWarnings("unchecked")V value =(V) s.readObject();putVal(hash(key), key, value,false,false);//执行插入动作}}}