HashMap源碼閱讀記錄

HashMap實現了map接口。從源碼發現HashMap底層維護着一個Entry對象數組,Entry是HashMap內部的一個靜態類,Entry是HashMap實現key-value對的一個基礎bean,它包含四個屬性,key和value就是map存儲的鍵值對,next屬性的做用是指向下一個entryjava

//Entry對象的四個屬性
 final K key;
 V value;
 Entry<K,V> next;
 int hash;

HashMap在初始化時若是不指定容量(capacity)和負載因子(load factor),則使用默認初始容量16,負載因子爲0.75,用戶指定的容量超過了最大容量(MAXIMUM_CAPACITY),HashMap會將用戶指定的容量強制改成默認最大容量,避免發生錯誤。看了源碼後,對hashmap有了必定的瞭解,下面是來自網上的源碼分析數組

package java.util;
import java.io.*;

public class HashMap<K,V>
    extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable
{

    /**
     * 默認初始容量,默認爲2的4次方 = 16,2的n次方是爲了加快hash計算速度,;;減小hash衝突,,,h & (length-1),,1111111
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**
     * 最大容量,默認爲2的30次方,
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * 默認負載因子,默認爲0.75
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     *當數組表還沒擴容的時候,一個共享的空表對象
     */
    static final Entry<?,?>[] EMPTY_TABLE = {};

    /**
     * 數組表,大小能夠改變,且大小必須爲2的冪
     */
    transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;

    /**
     * 當前Map中key-value映射的個數
     */
    transient int size;

    /**
     * 下次擴容閾值,當size > capacity * load factor時,開始擴容
     */
    int threshold;

    /**
     * 負載因子
     */
    final float loadFactor;

    /**
     * Hash表結構性修改次數,用於實現迭代器快速失敗行爲
     */
    transient int modCount;

    /**
     * 容量閾值,默認大小爲Integer.MAX_VALUE
     */
    static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;

    /**
     * 靜態內部類Holder,存放一些只能在虛擬機啓動後才能初始化的值
     */
    private static class Holder {

        /**
         * 容量閾值,初始化hashSeed的時候會用到該值
         */
        static final int ALTERNATIVE_HASHING_THRESHOLD;

        static {
            //獲取系統變量jdk.map.althashing.threshold
            String altThreshold = java.security.AccessController.doPrivileged(
                new sun.security.action.GetPropertyAction(
                    "jdk.map.althashing.threshold"));

            int threshold;
            try {
                threshold = (null != altThreshold)
                        ? Integer.parseInt(altThreshold)
                        : ALTERNATIVE_HASHING_THRESHOLD_DEFAULT;

                // jdk.map.althashing.threshold系統變量默認爲-1,若是爲-1,則將閾值設爲Integer.MAX_VALUE
                if (threshold == -1) {
                    threshold = Integer.MAX_VALUE;
                }
                //閾值須要爲正數
                if (threshold < 0) {
                    throw new IllegalArgumentException("value must be positive integer.");
                }
            } catch(IllegalArgumentException failed) {
                throw new Error("Illegal value for 'jdk.map.althashing.threshold'", failed);
            }

            ALTERNATIVE_HASHING_THRESHOLD = threshold;
        }
    }

    /**
     * 計算hash值的時候須要用到
     */
    transient int hashSeed = 0;

    /**
     * 生成一個空的HashMap,並指定其容量大小和負載因子
     *
     */
    public HashMap(int initialCapacity, float loadFactor) {
        //保證初始容量大於等於0
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        //保證初始容量不大於最大容量MAXIMUM_CAPACITY
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        
        //loadFactor小於0或爲無效數字
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        //負載因子
        this.loadFactor = loadFactor;
        //下次擴容大小
        threshold = initialCapacity;
        init();
    }

    /**
     * 生成一個空的HashMap,並指定其容量大小,負載因子使用默認的0.75
     *
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    /**
     * 生成一個空的HashMap,容量大小使用默認值16,負載因子使用默認值0.75
     */
    public HashMap() {
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
    }

    /**
     * 根據指定的map生成一個新的HashMap,負載因子使用默認值,初始容量大小爲Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,DEFAULT_INITIAL_CAPACITY)
     */
    public HashMap(Map<? extends K, ? extends V> m) {
        this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
                      DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
        inflateTable(threshold);

        putAllForCreate(m);
    }

    //返回>=number的最小2的n次方值,如number=5,則返回8
    private static int roundUpToPowerOf2(int number) {
        // assert number >= 0 : "number must be non-negative";
        return number >= MAXIMUM_CAPACITY
                ? MAXIMUM_CAPACITY
                : (number > 1) ? Integer.highestOneBit((number - 1) << 1) : 1;
    }

    /**
     * 對table擴容
     */
    private void inflateTable(int toSize) {
        // Find a power of 2 >= toSize
        //找一個值(2的n次方,且>=toSize)
        int capacity = roundUpToPowerOf2(toSize);

        //下次擴容閾值
        threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
        
        table = new Entry[capacity];
        initHashSeedAsNeeded(capacity);
    }

    // internal utilities

    void init() {
    }

    /**
     * 初始化hashSeed
     */
    final boolean initHashSeedAsNeeded(int capacity) {
        boolean currentAltHashing = hashSeed != 0;
        boolean useAltHashing = sun.misc.VM.isBooted() &&
                (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
        boolean switching = currentAltHashing ^ useAltHashing;
        if (switching) {
            hashSeed = useAltHashing
                ? sun.misc.Hashing.randomHashSeed(this)
                : 0;
        }
        return switching;
    }

    /**
     * 生成hash值
     */
    final int hash(Object k) {
        int h = hashSeed;
        
        //若是key是字符串,調用un.misc.Hashing.stringHash32生成hash值
        //Oracle表示能生成更好的hash分佈,不過這在jdk8中已刪除
        if (0 != h && k instanceof String) {
            return sun.misc.Hashing.stringHash32((String) k);
        }
        //一次散列,調用k的hashCode方法,與hashSeed作異或操做
        h ^= k.hashCode();

        // This function ensures that hashCodes that differ only by
        // constant multiples at each bit position have a bounded
        // number of collisions (approximately 8 at default load factor).
        //二次散列,
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }

    /**
     * 返回hash值的索引,採用除模取餘法,h & (length-1)操做 等價於 hash % length操做, 但&操做性能更優
     */
    static int indexFor(int h, int length) {
        // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
        return h & (length-1);
    }

    /**
     * 返回key-value映射個數
     */
    public int size() {
        return size;
    }

    /**
     * 判斷map是否爲空
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 返回指定key對應的value
     */
    public V get(Object key) {
        //key爲null狀況
        if (key == null)
            return getForNullKey();
        
        //根據key查找節點
        Entry<K,V> entry = getEntry(key);

        //返回key對應的值
        return null == entry ? null : entry.getValue();
    }

    /**
     * 查找key爲null的value,注意若是key爲null,則其hash值爲0,默認是放在table[0]裏的
     */
    private V getForNullKey() {
        if (size == 0) {
            return null;
        }
        //在table[0]的鏈表上查找key爲null的鍵值對,由於null默認是存在table[0]的桶裏
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {
            if (e.key == null)
                return e.value;
        }
        return null;
    }

    /**
     *判斷是否包含指定的key
     */
    public boolean containsKey(Object key) {
        return getEntry(key) != null;
    }

    /**
     * 根據key查找鍵值對,找不到返回null
     */
    final Entry<K,V> getEntry(Object key) {
        if (size == 0) {
            return null;
        }
        //若是key爲null,hash值爲0,不然調用hash方法,對key生成hash值
        int hash = (key == null) ? 0 : hash(key);
        
        //調用indexFor方法生成hash值的索引,遍歷該索引下的鏈表,查找key「相等」的鍵值對
        for (Entry<K,V> e = table[indexFor(hash, table.length)];
             e != null;
             e = e.next) {
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k))))
                return e;
        }
        return null;
    }

    /**
     * 向map存入一個鍵值對,若是key已存在,則覆蓋
     */
    public V put(K key, V value) {
        //數組爲空,對數組擴容
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
        
        //對key爲null的鍵值對調用putForNullKey處理
        if (key == null)
            return putForNullKey(value);
        
        //生成hash值
        int hash = hash(key);
        
        //生成hash值索引
        int i = indexFor(hash, table.length);
        
        //查找是否有key「相等」的鍵值對,有的話覆蓋
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }

        //操做次數加一,用於迭代器快速失敗行爲
        modCount++;
        
        //在指定hash值索引處的鏈表上增長該鍵值對
        addEntry(hash, key, value, i);
        return null;
    }

    /**
     * 存放key爲null的鍵值對,存放在索引爲0的鏈表上,已存在的話,替換
     */
    private V putForNullKey(V value) {
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {
            //已存在key爲null,則替換
            if (e.key == null) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
        //操做次數加一,用於迭代器快速失敗行爲
        modCount++;
        //在指定hash值索引處的鏈表上增長該鍵值對
        addEntry(0, null, value, 0);
        return null;
    }

    /**
     * 添加鍵值對
     */
    private void putForCreate(K key, V value) {
        //生成hash值
        int hash = null == key ? 0 : hash(key);
        
        //生成hash值索引,
        int i = indexFor(hash, table.length);

        /**
         * key「相等」,則替換
         */
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k)))) {
                e.value = value;
                return;
            }
        }
        //在指定索引處的鏈表上建立該鍵值對
        createEntry(hash, key, value, i);
    }
    
    //將制定map的鍵值對添加到map中
    private void putAllForCreate(Map<? extends K, ? extends V> m) {
        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
            putForCreate(e.getKey(), e.getValue());
    }

    /**
     * 對數組擴容
     */
    void resize(int newCapacity) {
        Entry[] oldTable = table;
        int oldCapacity = oldTable.length;
        
        if (oldCapacity == MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return;
        }
        
        //建立一個指定大小的數組
        Entry[] newTable = new Entry[newCapacity];
        
        transfer(newTable, initHashSeedAsNeeded(newCapacity));
        
        //table索引替換成新數組
        table = newTable;
        
        //從新計算閾值
        threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
    }

    /**
     * 拷貝舊的鍵值對到新的哈希表中
     */
    void transfer(Entry[] newTable, boolean rehash) {
        int newCapacity = newTable.length;
        //遍歷舊的數組
        for (Entry<K,V> e : table) {
            while(null != e) {
                Entry<K,V> next = e.next;
                if (rehash) {
                    e.hash = null == e.key ? 0 : hash(e.key);
                }
                //根據新的數組長度,從新計算索引,
                int i = indexFor(e.hash, newCapacity);
                
                //插入到鏈表表頭
                e.next = newTable[i];
                
                //將e放到索引爲i處
                newTable[i] = e;
                
                //將e設置成下個節點
                e = next;
            }
        }
    }

    /**
     * 將制定map的鍵值對put到本map,key「相等」的直接覆蓋
     */
    public void putAll(Map<? extends K, ? extends V> m) {
        int numKeysToBeAdded = m.size();
        if (numKeysToBeAdded == 0)
            return;

        //空map,擴容
        if (table == EMPTY_TABLE) {
            inflateTable((int) Math.max(numKeysToBeAdded * loadFactor, threshold));
        }

        /*
         * 判斷是否須要擴容
         */
        if (numKeysToBeAdded > threshold) {
            int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
            if (targetCapacity > MAXIMUM_CAPACITY)
                targetCapacity = MAXIMUM_CAPACITY;
            int newCapacity = table.length;
            while (newCapacity < targetCapacity)
                newCapacity <<= 1;
            if (newCapacity > table.length)
                resize(newCapacity);
        }

        //依次遍歷鍵值對,並put
        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
            put(e.getKey(), e.getValue());
    }

    /**
     * 移除指定key的鍵值對
     */
    public V remove(Object key) {
        Entry<K,V> e = removeEntryForKey(key);
        return (e == null ? null : e.value);
    }

    /**
     * 移除指定key的鍵值對
     */
    final Entry<K,V> removeEntryForKey(Object key) {
        if (size == 0) {
            return null;
        }
        //計算hash值及索引
        int hash = (key == null) ? 0 : hash(key);
        int i = indexFor(hash, table.length);
        
        Entry<K,V> prev = table[i];
        Entry<K,V> e = prev;

        //頭節點爲table[i]的單鏈表上執行刪除節點操做
        while (e != null) {
            Entry<K,V> next = e.next;
            Object k;
            //找到要刪除的節點
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k)))) {
                modCount++;
                size--;
                if (prev == e)
                    table[i] = next;
                else
                    prev.next = next;
                e.recordRemoval(this);
                return e;
            }
            prev = e;
            e = next;
        }

        return e;
    }

    /**
     * 刪除指定鍵值對對象(Entry對象)
     */
    final Entry<K,V> removeMapping(Object o) {
        if (size == 0 || !(o instanceof Map.Entry))
            return null;

        Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
        Object key = entry.getKey();
        int hash = (key == null) ? 0 : hash(key);
        //獲得數組索引
        int i = indexFor(hash, table.length);
        Entry<K,V> prev = table[i];
        Entry<K,V> e = prev;
        //開始遍歷該單鏈表
        while (e != null) {
            Entry<K,V> next = e.next;
            //找到節點
            if (e.hash == hash && e.equals(entry)) {
                modCount++;
                size--;
                if (prev == e)
                    table[i] = next;
                else
                    prev.next = next;
                e.recordRemoval(this);
                return e;
            }
            prev = e;
            e = next;
        }

        return e;
    }

    /**
     * 清空map,將table數組全部元素設爲null
     */
    public void clear() {
        modCount++;
        Arrays.fill(table, null);
        size = 0;
    }

    /**
     * 判斷是否含有指定value的鍵值對
     */
    public boolean containsValue(Object value) {
        if (value == null)
            return containsNullValue();

        Entry[] tab = table;
        //遍歷table數組
        for (int i = 0; i < tab.length ; i++)
            //遍歷每條單鏈表
            for (Entry e = tab[i] ; e != null ; e = e.next)
                if (value.equals(e.value))
                    return true;
        return false;
    }

    /**
     * 判斷是否含有value爲null的鍵值對
     */
    private boolean containsNullValue() {
        Entry[] tab = table;
        for (int i = 0; i < tab.length ; i++)
            for (Entry e = tab[i] ; e != null ; e = e.next)
                if (e.value == null)
                    return true;
        return false;
    }

    /**
     * 淺拷貝,鍵值對不復制
     */
    public Object clone() {
        HashMap<K,V> result = null;
        try {
            result = (HashMap<K,V>)super.clone();
        } catch (CloneNotSupportedException e) {
            // assert false;
        }
        if (result.table != EMPTY_TABLE) {
            result.inflateTable(Math.min(
                (int) Math.min(
                    size * Math.min(1 / loadFactor, 4.0f),
                    // we have limits...
                    HashMap.MAXIMUM_CAPACITY),
               table.length));
        }
        result.entrySet = null;
        result.modCount = 0;
        result.size = 0;
        result.init();
        result.putAllForCreate(this);

        return result;
    }

    //內部類,節點對象,每一個節點包含下個節點的引用
    static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next;
        int hash;

        /**
         * 建立節點
         */
        Entry(int h, K k, V v, Entry<K,V> n) {
            value = v;
            next = n;
            key = k;
            hash = h;
        }
        //獲取節點的key
        public final K getKey() {
            return key;
        }
        //獲取節點的value
        public final V getValue() {
            return value;
        }
        
        //設置新value,並返回舊的value
        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        //判斷key和value是否相同,兩個都「相等」,返回true
        public final boolean equals(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry e = (Map.Entry)o;
            Object k1 = getKey();
            Object k2 = e.getKey();
            if (k1 == k2 || (k1 != null && k1.equals(k2))) {
                Object v1 = getValue();
                Object v2 = e.getValue();
                if (v1 == v2 || (v1 != null && v1.equals(v2)))
                    return true;
            }
            return false;
        }

        public final int hashCode() {
            return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
        }

        public final String toString() {
            return getKey() + "=" + getValue();
        }

        /**
         * This method is invoked whenever the value in an entry is
         * overwritten by an invocation of put(k,v) for a key k that's already
         * in the HashMap.
         */
        void recordAccess(HashMap<K,V> m) {
        }

        /**
         * This method is invoked whenever the entry is
         * removed from the table.
         */
        void recordRemoval(HashMap<K,V> m) {
        }
    }

    /**
     * 添加新節點,若有必要,執行擴容操做
     */
    void addEntry(int hash, K key, V value, int bucketIndex) {
        //size超過閾值threshold進行容量擴充
        if ((size >= threshold) && (null != table[bucketIndex])) {
            resize(2 * table.length);
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);
        }

        createEntry(hash, key, value, bucketIndex);
    }

    /**
     * 插入單鏈表表頭
     */
    void createEntry(int hash, K key, V value, int bucketIndex) {
        Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<>(hash, key, value, e);
        size++;
    }

    //hashmap迭代器
    private abstract class HashIterator<E> implements Iterator<E> {
        Entry<K,V> next;        // 下個鍵值對索引
        int expectedModCount;   // 用於判斷快速失敗行爲
        int index;              // current slot
        Entry<K,V> current;     // current entry

        HashIterator() {
            expectedModCount = modCount;
            if (size > 0) { // advance to first entry
                Entry[] t = table;
                while (index < t.length && (next = t[index++]) == null)
                    ;
            }
        }

        public final boolean hasNext() {
            return next != null;
        }

        final Entry<K,V> nextEntry() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            Entry<K,V> e = next;
            if (e == null)
                throw new NoSuchElementException();

            if ((next = e.next) == null) {
                Entry[] t = table;
                while (index < t.length && (next = t[index++]) == null)
                    ;
            }
            current = e;
            return e;
        }

        public void remove() {
            if (current == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            Object k = current.key;
            current = null;
            HashMap.this.removeEntryForKey(k);
            expectedModCount = modCount;
        }
    }

    //ValueIterator迭代器
    private final class ValueIterator extends HashIterator<V> {
        public V next() {
            return nextEntry().value;
        }
    }
    //KeyIterator迭代器
    private final class KeyIterator extends HashIterator<K> {
        public K next() {
            return nextEntry().getKey();
        }
    }
    ////KeyIterator迭代器
    private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {
        public Map.Entry<K,V> next() {
            return nextEntry();
        }
    }

    // 返回迭代器方法
    Iterator<K> newKeyIterator()   {
        return new KeyIterator();
    }
    Iterator<V> newValueIterator()   {
        return new ValueIterator();
    }
    Iterator<Map.Entry<K,V>> newEntryIterator()   {
        return new EntryIterator();
    }


    // Views

    private transient Set<Map.Entry<K,V>> entrySet = null;

    /**
     * 返回一個set集合,包含key
     */
    public Set<K> keySet() {
        Set<K> ks = keySet;
        return (ks != null ? ks : (keySet = new KeySet()));
    }

    private final class KeySet extends AbstractSet<K> {
        public Iterator<K> iterator() {
            return newKeyIterator();
        }
        public int size() {
            return size;
        }
        public boolean contains(Object o) {
            return containsKey(o);
        }
        public boolean remove(Object o) {
            return HashMap.this.removeEntryForKey(o) != null;
        }
        public void clear() {
            HashMap.this.clear();
        }
    }

    /**
     * 返回一個value集合,包含value
     */
    public Collection<V> values() {
        Collection<V> vs = values;
        return (vs != null ? vs : (values = new Values()));
    }

    private final class Values extends AbstractCollection<V> {
        public Iterator<V> iterator() {
            return newValueIterator();
        }
        public int size() {
            return size;
        }
        public boolean contains(Object o) {
            return containsValue(o);
        }
        public void clear() {
            HashMap.this.clear();
        }
    }

    /**
     * 返回一個鍵值對集合
     */
    public Set<Map.Entry<K,V>> entrySet() {
        return entrySet0();
    }

    private Set<Map.Entry<K,V>> entrySet0() {
        Set<Map.Entry<K,V>> es = entrySet;
        return es != null ? es : (entrySet = new EntrySet());
    }

    private final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
        public Iterator<Map.Entry<K,V>> iterator() {
            return newEntryIterator();
        }
        public boolean contains(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry<K,V> e = (Map.Entry<K,V>) o;
            Entry<K,V> candidate = getEntry(e.getKey());
            return candidate != null && candidate.equals(e);
        }
        public boolean remove(Object o) {
            return removeMapping(o) != null;
        }
        public int size() {
            return size;
        }
        public void clear() {
            HashMap.this.clear();
        }
    }

    /**
     * map序列化,可實現深拷貝
     */
    private void writeObject(java.io.ObjectOutputStream s)
        throws IOException
    {
        // Write out the threshold, loadfactor, and any hidden stuff
        s.defaultWriteObject();

        // Write out number of buckets
        if (table==EMPTY_TABLE) {
            s.writeInt(roundUpToPowerOf2(threshold));
        } else {
           s.writeInt(table.length);
        }

        // Write out size (number of Mappings)
        s.writeInt(size);

        // Write out keys and values (alternating)
        if (size > 0) {
            for(Map.Entry<K,V> e : entrySet0()) {
                s.writeObject(e.getKey());
                s.writeObject(e.getValue());
            }
        }
    }

    private static final long serialVersionUID = 362498820763181265L;

    /**
     * 反序列化,讀取字節碼轉爲對象
     */
    private void readObject(java.io.ObjectInputStream s)
         throws IOException, ClassNotFoundException
    {
        // Read in the threshold (ignored), loadfactor, and any hidden stuff
        s.defaultReadObject();
        if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
            throw new InvalidObjectException("Illegal load factor: " +
                                               loadFactor);
        }

        // set other fields that need values
        table = (Entry<K,V>[]) EMPTY_TABLE;

        // Read in number of buckets
        s.readInt(); // ignored.

        // Read number of mappings
        int mappings = s.readInt();
        if (mappings < 0)
            throw new InvalidObjectException("Illegal mappings count: " +
                                               mappings);

        // capacity chosen by number of mappings and desired load (if >= 0.25)
        int capacity = (int) Math.min(
                    mappings * Math.min(1 / loadFactor, 4.0f),
                    // we have limits...
                    HashMap.MAXIMUM_CAPACITY);

        // allocate the bucket array;
        if (mappings > 0) {
            inflateTable(capacity);
        } else {
            threshold = capacity;
        }

        init();  // Give subclass a chance to do its thing.

        // Read the keys and values, and put the mappings in the HashMap
        for (int i = 0; i < mappings; i++) {
            K key = (K) s.readObject();
            V value = (V) s.readObject();
            putForCreate(key, value);
        }
    }

    // These methods are used when serializing HashSets
    int   capacity()     { return table.length; }
    float loadFactor()   { return loadFactor;   }
}
}
相關文章
相關標籤/搜索