1. 程式人生 > 實用技巧 >探索IdentityHashMap底層實現

探索IdentityHashMap底層實現

前沿

我也是第一次認識IdentityHashMap,在工作中從未使用過它,所以對它的使用場景可能並不是很瞭解,本文也僅僅針對基於JDK1.8的原始碼進行探索。IdentityHashMap的資料結構應該是如圖所示:

這個資料結構是我在看原始碼之前看了幾篇別人寫的文章所瞭解到的,個人喜歡在看原始碼對目標有所瞭解的習慣,緊接著才去深入它。

閱讀註釋

在IdentityHashMap中,對於兩個鍵只有在k1 == k2成立時才認為是相等的,而在HashMap中確實k1.equals(k2)成立是才被認為相等,前者是引用相等,而後者是物件相等

Identity可用於序列化或深拷貝或物件代理。

鍵值對允許存放null,同樣也是無序的。

IdentityHashMap屬於非執行緒安全,和集合中的其他類一樣迭代器都可能發生快速失敗。

線性探針雜湊表,這是對其資料結構的稱呼。

資料結構


    //可序列化、克隆
    public class IdentityHashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, java.io.Serializable, Cloneable {

        /**
         * 預設鍵值對個數
         * 雖然註釋上寫著是預設初始容量,但當你發現有這樣子的一段程式碼時:table = new Object[2 * initCapacity],你就會明白預設初始容量應該是64
         * 容量大小必須是2的冪次方,在新增節點時會先判斷當前節點的個數是否超過了容量的1/3,所以我認為1/3是載入因子
         * 
         * 為什麼必須是2的冪次方?
         * 在計算索引時用&程式碼了%,提升了效率,不過這導致了一個前提,就是必須是2的冪次方,為了是能夠取到容量區間中的每個索引,有人將這種做法稱為均勻分佈
         */
        private static final int DEFAULT_CAPACITY = 32;

        /**
         * 最小鍵值對個數
         * 
         * 為什麼最小是4?
         * 假設手動指定容量大小是1,則初始容量應該是2,在新增第一個節點時會先判斷當前節點的個數是否超過了容量的1/3,很顯然,2 * 1/3的結果都不足1,所以它會先擴容,擴容後再新增節點,由於擴容是需要消耗一定的成本,為何不在初始化時就設定較 * 高的值來避免此次擴容;那麼如果指定容量大小是2呢? 4 * 1/3 不足2,因為它的資料結構是同時儲存key與value,所以在儲存value時也必定會擴容,故也不行;那3就更不行了,畢竟要是2的冪次方,所以4屬於最小指定容量值
         */
        private static final int MINIMUM_CAPACITY = 4;

        /**
         * 最大鍵值對個數
         * 雖然註釋上寫著是最大容量,但實際上並不是,此數值用於當建構函式中指定的容量過高時會直接該數值,而當你發現有這樣子一句程式碼時:table = new Object[2 * initCapacity]; 你就會發現實際上最大的容量應該是 1<<30才對
         * 實際上,線性探針表中能儲存的節點個數不能超過 1<<<30 - 1 個,因為它至少有一個位置是儲存了null,用來避免死迴圈
         */
        private static final int MAXIMUM_CAPACITY = 1 << 29;

        /**
         * 線性探針表
         */
        transient Object[] table;

        /**
         * 線性探針表中儲存的節點個數
         */
        int size;

        /** 
         * 結構被修改的次數
         * 該成員屬性是用於檢測迭代器的快速失敗
         */
        transient int modCount;

        /**
         * 代表鍵為null
         */
        static final Object NULL_KEY = new Object();

        /**
         * 快取entrySet方法的返回值
         */
        private transient Set<Map.Entry<K,V>> entrySet;

    }

建構函式


    /**
     * 採用預設鍵值對個數初始化
     */
    public IdentityHashMap() {
        init(DEFAULT_CAPACITY);
    }

    /**
     * 指定鍵值對個數來初始化
     * @param expectedMaxSize 指定鍵值對個數
     */
    public IdentityHashMap(int expectedMaxSize) {
        if (expectedMaxSize < 0)
            throw new IllegalArgumentException("expectedMaxSize is negative: "
                                               + expectedMaxSize);
        init(capacity(expectedMaxSize));
    }

    /**
     * 指定鍵值對個數進行初始化,並將指定集合新增到線性探針表中
     * @param m 指定集合
     */
    public IdentityHashMap(Map<? extends K, ? extends V> m) {
        // Allow for a bit of growth
        this((int) ((1 + m.size()) * 1.1));
        putAll(m);
    }


簡單方法


    /**
     * 倘若鍵為null則採用NULL_KEY作為鍵
     * 正如方法名一樣,隱藏Null
     * @param key 指定鍵
     * @return NULL_KEY或指定鍵
     */
    private static Object maskNull(Object key) {
        return (key == null ? NULL_KEY : key);
    }

    /**
     * 倘若鍵為NULL_KEY則返回null
     * 正如方法名一樣,揭露Null
     * @param key 線性探針表中的鍵
     * @return null或指定鍵
     */
    static final Object unmaskNull(Object key) {
        return (key == NULL_KEY ? null : key);
    }

    /**
     * 調整指定鍵值對個數
     * Integer.highestOneBit 返回只含有二進位制中最高位(從左到右第一個數字為1)的十進位制,如15對應的二進位制是1111,結果是1000,也就是數字8
     * 這裡有一點我覺得程式碼寫的不夠完美,假設expectedMaxSize = 3,意思我可能要儲存3個鍵值對,而它最終的容量是16,那麼在我新增最後一對鍵值對時,它仍然會進行擴容,個人覺得設計的不夠完美
     * @param expectedMaxSize 指定鍵值對個數
     * @return 調整後的鍵值對個數
     */
    private static int capacity(int expectedMaxSize) {
        return
            (expectedMaxSize > MAXIMUM_CAPACITY / 3) ? MAXIMUM_CAPACITY :
            (expectedMaxSize <= 2 * MINIMUM_CAPACITY / 3) ? MINIMUM_CAPACITY :
            Integer.highestOneBit(expectedMaxSize + (expectedMaxSize << 1));
    }

    /**
     * 指定鍵值對個數來初始化雜湊探針表
     * 由於引數代表著鍵值對個數,相當於是2倍的節點個數,故在初始化時 * 2
     * @param initCapacity 指定鍵值對個數
     */
    private void init(int initCapacity) {
        table = new Object[2 * initCapacity];
    }

    /**
     * 獲取雜湊探針表中節點的個數
     * @return 節點的個數
     */
    public int size() {
        return size;
    }

    /**
     * 判斷雜湊探針表是否為空
     * @return 雜湊探針表是否為空
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 在指定區間內獲取偶數索引位置
     * 為什麼是偶數位置?
     * 因為它的資料結構是按照 | key | value | key1 | value1 | 的形式進行儲存,導致了鍵是儲存在偶數位置上,而值是儲存在奇數位置上
     * 它採用的System.identityHashCode,該方法的結果與Object#hashCode的結果是一樣的,只不過這樣子就調不到開發人員自己覆寫的hashCode方法
     * @param x 指定鍵
     * @param length 指定容量大小
     * @return 偶數索引位置
     */
    private static int hash(Object x, int length) {
        int h = System.identityHashCode(x);
        /**
         * (h << 1) - (h <<8) 
         * h * Math.pow(2,1) - h * Math.pow(2,8) -> -h * (Math.pow(2,8) - Math.pow(2,1)) -> -h * 2 * (Math.pow(2,7) - 1) -> -h * 2 * 127 -> -h * 127 * 2
         * 簡化後的結果正好跟註釋對應上,不過它始終沒解釋為啥是乘以-127,目前只知道 * 2是一定會得到偶數,因為它相當於進行了左移,去掉了最右邊的一位,即1
         * 然後偶數 & (length - 1) 最終是確定索引只可能是該區間內上的某一個偶數位置
         */
        return ((h << 1) - (h << 8)) & (length - 1);
    }

    /**
     * 獲取下一個偶數索引位置
     * 若下一個偶數索引位置超過了雜湊探針表的容量大小,則從頭開始,相當於在迴圈遍歷雜湊探針表
     * @param i 當前索引位置
     * @param len 表的容量大小
     * @return 下一個偶數索引位置
     */
    private static int nextKeyIndex(int i, int len) {
        return (i + 2 < len ? i + 2 : 0);
    }

    /**
     * 對雜湊探針表進行擴容
     * 新表是舊錶的2倍,原來在舊錶中節點重新雜湊到新表上
     * @param newCapacity 指定容量大小
     * @return 是否擴容成功
     */
    private boolean resize(int newCapacity) {
        int newLength = newCapacity * 2;

        Object[] oldTable = table;
        int oldLength = oldTable.length;
        if (oldLength == 2 * MAXIMUM_CAPACITY) {
            if (size == MAXIMUM_CAPACITY - 1) //最大節點的個數不能超過 MAXIMUM_CAPACITY - 1,因為有一個位置要儲存Null,避免死迴圈
                throw new IllegalStateException("Capacity exhausted.");
            return false;
        }
        if (oldLength >= newLength)
            return false;

        Object[] newTable = new Object[newLength];

        for (int j = 0; j < oldLength; j += 2) { //查詢偶數位置上的鍵
            //擴容後將鍵值對重新雜湊到新表上
            Object key = oldTable[j];
            if (key != null) {
                Object value = oldTable[j+1];
                oldTable[j] = null;
                oldTable[j+1] = null;
                int i = hash(key, newLength);
                while (newTable[i] != null)
                    i = nextKeyIndex(i, newLength);
                newTable[i] = key;
                newTable[i + 1] = value;
            }
        }
        table = newTable;
        return true;
    }

    /**
     * 雜湊探針表中是否包含指定鍵
     * @param key 指定鍵
     * @return 是否包含指定鍵
     */
    public boolean containsKey(Object key) {
        Object k = maskNull(key);
        Object[] tab = table;
        int len = tab.length;
        int i = hash(k, len);
        while (true) {
            Object item = tab[i];
            if (item == k)
                return true;
            if (item == null)
                return false;
            i = nextKeyIndex(i, len);
        }
    }

    /**
     * 雜湊探針表中是否包含指定值
     * @param value 指定值
     * @return 是否包含指定值
     */
    public boolean containsValue(Object value) {
        Object[] tab = table;
        for (int i = 1; i < tab.length; i += 2)
            if (tab[i] == value && tab[i - 1] != null)
                return true;

        return false;
    }

    /**
     * 雜湊探針表中是否包含指定鍵值對
     * @param key 指定鍵
     * @param value 指定值
     * @return 是否包含指定鍵值對
     */
    private boolean containsMapping(Object key, Object value) {
        Object k = maskNull(key);
        Object[] tab = table;
        int len = tab.length;
        int i = hash(k, len);
        while (true) {
            Object item = tab[i];
            if (item == k)
                return tab[i + 1] == value;
            if (item == null)
                return false;
            i = nextKeyIndex(i, len);
        }
    }

    /**
     * 刪除節點後重新雜湊所有可能衝突的節點
     * | key | value | key1 | value1 | key2 | value2 | -> | key1 | value1 | key2 | value2 | null | null |
     * 該方法的實現較為混亂
     * @param d 指定索引位置
     */
    private void closeDeletion(int d) {
        // Adapted from Knuth Section 6.4 Algorithm R
        Object[] tab = table;
        int len = tab.length;

        // Look for items to swap into newly vacated slot
        // starting at index immediately following deletion,
        // and continuing until a null slot is seen, indicating
        // the end of a run of possibly-colliding keys.
        Object item;
        for (int i = nextKeyIndex(d, len); (item = tab[i]) != null;
             i = nextKeyIndex(i, len) ) {
            int r = hash(item, len);
            if ((i < r && (r <= d || d <= i)) || (r <= d && d <= i)) {
                tab[d] = item;
                tab[d + 1] = tab[i + 1];
                tab[i] = null;
                tab[i + 1] = null;
                d = i;
            }
        }
    }

    /**
     * 清空
     */
    public void clear() {
        modCount++;
        Object[] tab = table;
        for (int i = 0; i < tab.length; i++)
            tab[i] = null;
        size = 0;
    }

    /**
     * 比較當前物件與指定物件是否相等
     * @param o 指定物件
     * @return 是否相等
     */
    public boolean equals(Object o) {
        if (o == this) {
            return true;
        } else if (o instanceof IdentityHashMap) {
            IdentityHashMap<?,?> m = (IdentityHashMap<?,?>) o;
            if (m.size() != size)
                return false;

            Object[] tab = m.table;
            for (int i = 0; i < tab.length; i+=2) {
                Object k = tab[i];
                if (k != null && !containsMapping(k, tab[i + 1]))
                    return false;
            }
            return true;
        } else if (o instanceof Map) {
            Map<?,?> m = (Map<?,?>)o;
            return entrySet().equals(m.entrySet());
        } else {
            return false;  // o is not a Map
        }
    }

    /**
     * 獲取雜湊值
     * @return 雜湊值
     */
    public int hashCode() {
        int result = 0;
        Object[] tab = table;
        for (int i = 0; i < tab.length; i +=2) {
            Object key = tab[i];
            if (key != null) {
                Object k = unmaskNull(key);
                result += System.identityHashCode(k) ^
                          System.identityHashCode(tab[i + 1]);
            }
        }
        return result;
    }

    /**
     * 淺拷貝
     * @return 克隆後的物件
     */
    public Object clone() {
        try {
            IdentityHashMap<?,?> m = (IdentityHashMap<?,?>) super.clone();
            m.entrySet = null;
            m.table = table.clone();
            return m;
        } catch (CloneNotSupportedException e) {
            throw new InternalError(e);
        }
    }

    /**
     * 迭代器
     */
    private abstract class IdentityHashMapIterator<T> implements Iterator<T> {
        //當前索引位置
        int index = (size != 0 ? 0 : table.length);

        //結構修改次數
        int expectedModCount = modCount;

        //移除節點前需要先獲取當前索引位置,即先呼叫nextIndex後才能移除,下一次移除仍然需要先呼叫該方法
        int lastReturnedIndex = -1;

        //是否是有效索引
        boolean indexValid; // To avoid unnecessary next computation

        //雜湊探針表
        Object[] traversalTable = table; // reference to main table or copy

        /**
         * 從當前索引位置開始後續是否有下一個鍵
         * @return 是否有下一個鍵
         */
        public boolean hasNext() {
            Object[] tab = traversalTable;
            for (int i = index; i < tab.length; i+=2) {
                Object key = tab[i];
                if (key != null) {
                    index = i;
                    return indexValid = true;
                }
            }
            index = tab.length;
            return false;
        }

        /**
         * 獲取下一個索引
         * @return 下一個索引
         */
        protected int nextIndex() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            if (!indexValid && !hasNext())
                throw new NoSuchElementException();

            indexValid = false;
            lastReturnedIndex = index;
            index += 2;
            return lastReturnedIndex;
        }

        /**
         * 移除當前節點
         */
        public void remove() {
            if (lastReturnedIndex == -1)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();

            expectedModCount = ++modCount;
            int deletedSlot = lastReturnedIndex;
            lastReturnedIndex = -1;
            // back up index to revisit new contents after deletion
            index = deletedSlot;
            indexValid = false;

            Object[] tab = traversalTable;
            int len = tab.length;

            int d = deletedSlot;
            Object key = tab[d];
            tab[d] = null;        // vacate the slot
            tab[d + 1] = null;

            // If traversing a copy, remove in real table.
            // We can skip gap-closure on copy.
            if (tab != IdentityHashMap.this.table) {
                IdentityHashMap.this.remove(key);
                expectedModCount = modCount;
                return;
            }

            size--;

            //在刪除節點後所有可能衝突的節點會被重新雜湊,但是遍歷的索引確實不變的,這也就是導致了移動後的某些節點可能會遍歷不到,所以它在變化前做了陣列的拷貝以便能夠正常訪問
            Object item;
            for (int i = nextKeyIndex(d, len); (item = tab[i]) != null;
                 i = nextKeyIndex(i, len)) {
                int r = hash(item, len);
                // See closeDeletion for explanation of this conditional
                if ((i < r && (r <= d || d <= i)) ||
                    (r <= d && d <= i)) {

                    if (i < deletedSlot && d >= deletedSlot &&
                        traversalTable == IdentityHashMap.this.table) {
                        int remaining = len - deletedSlot;
                        Object[] newTable = new Object[remaining];
                        System.arraycopy(tab, deletedSlot,
                                         newTable, 0, remaining);
                        traversalTable = newTable;
                        index = 0;
                    }

                    tab[d] = item;
                    tab[d + 1] = tab[i + 1];
                    tab[i] = null;
                    tab[i + 1] = null;
                    d = i;
                }
            }
        }
    }

    /** 
     * 包含所有鍵的迭代器
     */
    private class KeyIterator extends IdentityHashMapIterator<K> {
        @SuppressWarnings("unchecked")
        public K next() {
            return (K) unmaskNull(traversalTable[nextIndex()]);
        }
    }

    /**
     * 包含所有值的迭代器
     */
    private class ValueIterator extends IdentityHashMapIterator<V> {
        @SuppressWarnings("unchecked")
        public V next() {
            return (V) traversalTable[nextIndex() + 1];
        }
    }

    /**
     * 包含所有鍵值對的迭代器,都是類似的程式碼就不做解釋了
     */
    private class EntryIterator extends IdentityHashMapIterator<Map.Entry<K,V>> {
        private Entry lastReturnedEntry;

        public Map.Entry<K,V> next() {
            lastReturnedEntry = new Entry(nextIndex());
            return lastReturnedEntry;
        }

        public void remove() {
            lastReturnedIndex =
                ((null == lastReturnedEntry) ? -1 : lastReturnedEntry.index);
            super.remove();
            lastReturnedEntry.index = lastReturnedIndex;
            lastReturnedEntry = null;
        }

        private class Entry implements Map.Entry<K,V> {
            private int index;

            private Entry(int index) {
                this.index = index;
            }

            @SuppressWarnings("unchecked")
            public K getKey() {
                checkIndexForEntryUse();
                return (K) unmaskNull(traversalTable[index]);
            }

            @SuppressWarnings("unchecked")
            public V getValue() {
                checkIndexForEntryUse();
                return (V) traversalTable[index+1];
            }

            @SuppressWarnings("unchecked")
            public V setValue(V value) {
                checkIndexForEntryUse();
                V oldValue = (V) traversalTable[index+1];
                traversalTable[index+1] = value;
                // if shadowing, force into main table
                if (traversalTable != IdentityHashMap.this.table)
                    put((K) traversalTable[index], value);
                return oldValue;
            }

            public boolean equals(Object o) {
                if (index < 0)
                    return super.equals(o);

                if (!(o instanceof Map.Entry))
                    return false;
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                return (e.getKey() == unmaskNull(traversalTable[index]) &&
                       e.getValue() == traversalTable[index+1]);
            }

            public int hashCode() {
                if (lastReturnedIndex < 0)
                    return super.hashCode();

                return (System.identityHashCode(unmaskNull(traversalTable[index])) ^
                       System.identityHashCode(traversalTable[index+1]));
            }

            public String toString() {
                if (index < 0)
                    return super.toString();

                return (unmaskNull(traversalTable[index]) + "="
                        + traversalTable[index+1]);
            }

            private void checkIndexForEntryUse() {
                if (index < 0)
                    throw new IllegalStateException("Entry was removed");
            }
        }
    }

   /**
     * 獲取包含所有鍵的集合
     * @return 包含所有鍵的Set集合 
     */
    public Set<K> keySet() {
        Set<K> ks = keySet;
        if (ks == null) {
            ks = new KeySet();
            keySet = ks;
        }
        return ks;
    }

    /**
     * 包含雜湊探針表中所有鍵的集合
     */
    private class KeySet extends AbstractSet<K> {
        public Iterator<K> iterator() {
            return new KeyIterator();
        }
        public int size() {
            return size;
        }
        public boolean contains(Object o) {
            return containsKey(o);
        }
        public boolean remove(Object o) {
            int oldSize = size;
            IdentityHashMap.this.remove(o);
            return size != oldSize;
        }
        public boolean removeAll(Collection<?> c) {
            Objects.requireNonNull(c);
            boolean modified = false;
            for (Iterator<K> i = iterator(); i.hasNext(); ) {
                if (c.contains(i.next())) {
                    i.remove();
                    modified = true;
                }
            }
            return modified;
        }
        public void clear() {
            IdentityHashMap.this.clear();
        }
        public int hashCode() {
            int result = 0;
            for (K key : this)
                result += System.identityHashCode(key);
            return result;
        }
        public Object[] toArray() {
            return toArray(new Object[0]);
        }
        @SuppressWarnings("unchecked")
        public <T> T[] toArray(T[] a) {
            int expectedModCount = modCount;
            int size = size();
            if (a.length < size)
                a = (T[]) Array.newInstance(a.getClass().getComponentType(), size);
            Object[] tab = table;
            int ti = 0;
            for (int si = 0; si < tab.length; si += 2) {
                Object key;
                if ((key = tab[si]) != null) { // key present ?
                    // more elements than expected -> concurrent modification from other thread
                    if (ti >= size) {
                        throw new ConcurrentModificationException();
                    }
                    a[ti++] = (T) unmaskNull(key); // unmask key
                }
            }
            // fewer elements than expected or concurrent modification from other thread detected
            if (ti < size || expectedModCount != modCount) {
                throw new ConcurrentModificationException();
            }
            // final null marker as per spec
            if (ti < a.length) {
                a[ti] = null;
            }
            return a;
        }

        public Spliterator<K> spliterator() {
            return new KeySpliterator<>(IdentityHashMap.this, 0, -1, 0, 0);
        }
    }

    /**
     * 獲取包含所有值的物件
     * @return 包含所有值的物件
     */
    public Collection<V> values() {
        Collection<V> vs = values;
        if (vs == null) {
            vs = new Values();
            values = vs;
        }
        return vs;
    }

    /**
     * 包含所有值的物件
     */
    private class Values extends AbstractCollection<V> {
        public Iterator<V> iterator() {
            return new ValueIterator();
        }
        public int size() {
            return size;
        }
        public boolean contains(Object o) {
            return containsValue(o);
        }
        public boolean remove(Object o) {
            for (Iterator<V> i = iterator(); i.hasNext(); ) {
                if (i.next() == o) {
                    i.remove();
                    return true;
                }
            }
            return false;
        }
        public void clear() {
            IdentityHashMap.this.clear();
        }
        public Object[] toArray() {
            return toArray(new Object[0]);
        }
        @SuppressWarnings("unchecked")
        public <T> T[] toArray(T[] a) {
            int expectedModCount = modCount;
            int size = size();
            if (a.length < size)
                a = (T[]) Array.newInstance(a.getClass().getComponentType(), size);
            Object[] tab = table;
            int ti = 0;
            for (int si = 0; si < tab.length; si += 2) {
                if (tab[si] != null) { // key present ?
                    // more elements than expected -> concurrent modification from other thread
                    if (ti >= size) {
                        throw new ConcurrentModificationException();
                    }
                    a[ti++] = (T) tab[si+1]; // copy value
                }
            }
            // fewer elements than expected or concurrent modification from other thread detected
            if (ti < size || expectedModCount != modCount) {
                throw new ConcurrentModificationException();
            }
            // final null marker as per spec
            if (ti < a.length) {
                a[ti] = null;
            }
            return a;
        }

        public Spliterator<V> spliterator() {
            return new ValueSpliterator<>(IdentityHashMap.this, 0, -1, 0, 0);
        }
    }

    /**
     * 獲取包含所有鍵值對的集合
     * @return 包含所有鍵值對的集合
     */
    public Set<Map.Entry<K,V>> entrySet() {
        Set<Map.Entry<K,V>> es = entrySet;
        if (es != null)
            return es;
        else
            return entrySet = new EntrySet();
    }

     /**
     * 包含所有鍵值對的集合
     */
    private class EntrySet extends AbstractSet<Map.Entry<K,V>> {
        public Iterator<Map.Entry<K,V>> iterator() {
            return new EntryIterator();
        }
        public boolean contains(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry<?,?> entry = (Map.Entry<?,?>)o;
            return containsMapping(entry.getKey(), entry.getValue());
        }
        public boolean remove(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry<?,?> entry = (Map.Entry<?,?>)o;
            return removeMapping(entry.getKey(), entry.getValue());
        }
        public int size() {
            return size;
        }
        public void clear() {
            IdentityHashMap.this.clear();
        }
        public boolean removeAll(Collection<?> c) {
            Objects.requireNonNull(c);
            boolean modified = false;
            for (Iterator<Map.Entry<K,V>> i = iterator(); i.hasNext(); ) {
                if (c.contains(i.next())) {
                    i.remove();
                    modified = true;
                }
            }
            return modified;
        }

        public Object[] toArray() {
            return toArray(new Object[0]);
        }

        @SuppressWarnings("unchecked")
        public <T> T[] toArray(T[] a) {
            int expectedModCount = modCount;
            int size = size();
            if (a.length < size)
                a = (T[]) Array.newInstance(a.getClass().getComponentType(), size);
            Object[] tab = table;
            int ti = 0;
            for (int si = 0; si < tab.length; si += 2) {
                Object key;
                if ((key = tab[si]) != null) { // key present ?
                    // more elements than expected -> concurrent modification from other thread
                    if (ti >= size) {
                        throw new ConcurrentModificationException();
                    }
                    a[ti++] = (T) new AbstractMap.SimpleEntry<>(unmaskNull(key), tab[si + 1]);
                }
            }
            // fewer elements than expected or concurrent modification from other thread detected
            if (ti < size || expectedModCount != modCount) {
                throw new ConcurrentModificationException();
            }
            // final null marker as per spec
            if (ti < a.length) {
                a[ti] = null;
            }
            return a;
        }

        public Spliterator<Map.Entry<K,V>> spliterator() {
            return new EntrySpliterator<>(IdentityHashMap.this, 0, -1, 0, 0);
        }
    }

    /**
     * 自定義序列化
     * @param s 輸出流
     */
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException  {
        // Write out and any hidden stuff
        s.defaultWriteObject();

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

        // Write out keys and values (alternating)
        Object[] tab = table;
        for (int i = 0; i < tab.length; i += 2) {
            Object key = tab[i];
            if (key != null) {
                s.writeObject(unmaskNull(key));
                s.writeObject(tab[i + 1]);
            }
        }
    }

    /**
     * 自定義反序列化
     * @param s 輸入流
     */
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException  {
        // Read in any hidden stuff
        s.defaultReadObject();

        // Read in size (number of Mappings)
        int size = s.readInt();
        if (size < 0)
            throw new java.io.StreamCorruptedException
                ("Illegal mappings count: " + size);
        int cap = capacity(size);
        SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, cap);
        init(cap);

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

    /**
     * 反序列化時將鍵值對儲存到雜湊探針表上
     * @param key 指定鍵
     * @param value 指定值
     */
    private void putForCreate(K key, V value) throws java.io.StreamCorruptedException {
        Object k = maskNull(key);
        Object[] tab = table;
        int len = tab.length;
        int i = hash(k, len);

        Object item;
        while ( (item = tab[i]) != null) {
            if (item == k)
                throw new java.io.StreamCorruptedException();
            i = nextKeyIndex(i, len);
        }
        tab[i] = k;
        tab[i + 1] = value;
    }

    /**
     * 遍歷雜湊探針表並執行指定動作
     * @param action 指定動作
     */
    @SuppressWarnings("unchecked")
    @Override
    public void forEach(BiConsumer<? super K, ? super V> action) {
        Objects.requireNonNull(action);
        int expectedModCount = modCount;

        Object[] t = table;
        for (int index = 0; index < t.length; index += 2) {
            Object k = t[index];
            if (k != null) {
                action.accept((K) unmaskNull(k), (V) t[index + 1]);
            }

            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
        }
    }

    /**
     * 遍歷雜湊探針表並執行指定動作後獲取新值,利用新值替換所有節點的舊值
     * @param function 指定動作
     */
    @SuppressWarnings("unchecked")
    @Override
    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
        Objects.requireNonNull(function);
        int expectedModCount = modCount;

        Object[] t = table;
        for (int index = 0; index < t.length; index += 2) {
            Object k = t[index];
            if (k != null) {
                t[index + 1] = function.apply((K) unmaskNull(k), (V) t[index + 1]);
            }

            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
        }
    }

新增節點


    /**
     * 新增節點
     * 先獲取偶數索引位置,若該位置上已經存在節點且兩者的節點相等,則進行替換,若兩者的節點不相等則繼續往下查詢偶數索引位置,直到偶數位置上不存在節點時才跳出迴圈
     * 在上面我們提到,在最大鍵值對中必須有一個地方存在null,否則會陷入死迴圈,而這裡正好也是說明了這一點,要是在最大鍵值對中所有的偶數位置上都已經填充了節點,那麼它會一直查詢,陷入了一個環形的查詢中,反正就是死迴圈了
     * @param key 指定鍵
     * @param value 指定值
     * @return null或舊值
     */
    public V put(K key, V value) {
        final Object k = maskNull(key);

        retryAfterResize: for (;;) {
            final Object[] tab = table;
            final int len = tab.length;
            int i = hash(k, len);

            for (Object item; (item = tab[i]) != null;
                 i = nextKeyIndex(i, len)) {
                if (item == k) { //若新增的節點與當前偶數索引位置上的節點相等,將新值替換舊值
                    @SuppressWarnings("unchecked")
                        V oldValue = (V) tab[i + 1];
                    tab[i + 1] = value;
                    return oldValue;
                }
            }

            final int s = size + 1;
            /** 
             * s + (s << 1) -> 3 * s
             * 新增節點後是否超過容量的1/3,若超過則進行擴容,擴容成功後要在新表中重新查詢偶數索引位置,若擴容失敗或不需要擴容則直接儲存節點
             */
            if (s + (s << 1) > len && resize(len))
                continue retryAfterResize; //程式碼又回到for迴圈上

            modCount++;
            tab[i] = k;
            tab[i + 1] = value;
            size = s;
            return null;
        }
    }

    /**
     * 新增指定集合到線性探針表中
     * @param m 指定集合
     */
    public void putAll(Map<? extends K, ? extends V> m) {
        int n = m.size();
        if (n == 0)
            return;
        if (n > size)
            resize(capacity(n)); //保守擴容

        for (Entry<? extends K, ? extends V> e : m.entrySet())
            put(e.getKey(), e.getValue());
    }

獲取節點


    /**
     * 通過指定鍵獲取值
     * @param key 指定鍵
     * @return null或值
     */
    public V get(Object key) {
        Object k = maskNull(key);
        Object[] tab = table;
        int len = tab.length;
        int i = hash(k, len);
        while (true) {
            Object item = tab[i];
            if (item == k)
                return (V) tab[i + 1];
            if (item == null)
                return null;
            i = nextKeyIndex(i, len);
        }
    }


移除節點


    /**
     * 通過指定鍵移除節點
     * 移除節點後會重新雜湊所有可能衝突的節點
     * @param key 指定鍵
     * @return null或舊值
     */
    public V remove(Object key) {
        Object k = maskNull(key);
        Object[] tab = table;
        int len = tab.length;
        int i = hash(k, len);

        while (true) {
            Object item = tab[i];
            if (item == k) {
                modCount++;
                size--;
                @SuppressWarnings("unchecked")
                    V oldValue = (V) tab[i + 1];
                tab[i + 1] = null;
                tab[i] = null;
                closeDeletion(i); //刪除節點後重新雜湊所有可能衝突的節點
                return oldValue;
            }
            if (item == null)
                return null;
            i = nextKeyIndex(i, len);
        }
    }

    /**
     * 通過鍵值對移除節點
     * @param key 指定鍵
     * @param value 指定值
     * @return 是否移除成功
     */
    private boolean removeMapping(Object key, Object value) {
        Object k = maskNull(key);
        Object[] tab = table;
        int len = tab.length;
        int i = hash(k, len);

        while (true) {
            Object item = tab[i];
            if (item == k) {
                if (tab[i + 1] != value)
                    return false;
                modCount++;
                size--;
                tab[i] = null;
                tab[i + 1] = null;
                closeDeletion(i);
                return true;
            }
            if (item == null)
                return false;
            i = nextKeyIndex(i, len);
        }
    }

總結

  • IdentityHashMap的資料結構是線性探針表

  • IdentityHashMap採用的是引用相等,而HashMap採用的是物件相等

  • IdentityHashMap預設容量大小是64,個人認為載入因子是1/3。

  • IdentityHashMap的容量大小必須是2的冪次方。

  • IdentityHashMap用於序列化或深拷貝、代理場景中,不過即使這麼說,我還是沒能感受到它的用處。

  • IdentityHashMap無序、不可重複、非執行緒安全。

  • IdentityHashMap的鍵值對允許存放null。

  • 新增節點流程:首先獲取索引位置,接著若發現當前位置上不存在節點則直接新增皆可,若發現當前位置上已經存在節點了則比較兩者是否相等(採用 k1 == k2的方式),若相等則說明重複進行替換值即可,若不相等說明發生衝突,它會往後查抄偶數索引位置,直到發現偶數索引位置上不存在節點時才進行儲存。

  • 擴容機制:在新增元素時判斷當前節點個數是否超過了容量的1/3,若超過則以2倍大小進行擴容,擴容時對雜湊探針表中的所有節點進行重新雜湊,擴容結束後從重新走上面的新增節點流程,因為節點的索引位置已經發生變化;最大鍵值對是 1 << 29,最小鍵值對是 4,雖說最大鍵值對是1 << 29,但實際上能儲存的最大鍵值對是 1 << 29 -1,因為它要保留一個null來防止死迴圈,在程式中它採用的是不斷遍歷雜湊探針表來獲取偶數位置上不存在節點的索引,若所有位置上都填充了節點,就會陷入死迴圈中,所以至少要有這樣子的一個null。

  • 刪除節點流程:在刪除節點後,它會重新雜湊所有可能衝突的節點。按照上面的新增節點流程中我們知道,兩個節點即使發生衝突了也只是找其他的位置進行儲存,這和不衝突的情況下進行儲存並沒有什麼區別,所以在刪除節點後,它會重新雜湊所有節點。

重點關注

resize put remove