基於源碼的Java集合框架學習⑪ IdentityHashMap

類 IdentityHashMap<K,V>

此類利用哈希表實現 Map 接口,比較鍵(和值)時使用引用相等性代替對象相等性。換句話說,在 IdentityHashMap 中,當且僅當 (k1 == k2) 時,才認爲兩個鍵 k1 和 k2 相等(在正常 Map 實現(如 HashMap)中,當且僅當滿足下列條件時才認爲兩個鍵 k1 和 k2 相等:(k1 == null ? k2 == null : e1.equals(e2)))。

此類不是 通用 Map 實現!此類實現 Map 接口時,它有意違反 Map 的常規協定,該協定在比較對象時強制使用 equals 方法。此類設計僅用於其中需要引用相等性語義的罕見情況。

此類的典型用法是拓撲保留對象圖形轉換,如序列化或深層複製。要執行這樣的轉換,程序必須維護用於跟蹤所有已處理對象引用的“節點表”。節點表一定不等於不同對象,即使它們偶然相等也如此。此類的另一種典型用法是維護代理對象。例如,調試設施可能希望爲正在調試程序中的每個對象維護代理對象。

此類提供所有的可選映射操作,並且允許 null 值和 null 鍵。此類對映射的順序不提供任何保證;特別是不保證順序隨時間的推移保持不變。

此類提供基本操作(get 和 put)的穩定性能,假定系統標識了將桶間元素正確分開的哈希函數 (System.identityHashCode(Object))。

此類具有一個調整參數(影響性能但不影響語義):expected maximum size。此參數是希望映射保持的鍵值映射關係最大數。在內部,此參數用於確定最初組成哈希表的桶數。未指定所期望的最大數量和桶數之間的確切關係。

如果映射的大小(鍵值映射關係數)已經超過期望的最大數量,則桶數會增加,增加桶數(“重新哈希”)可能相當昂貴,因此創建具有足夠大的期望最大數量的標識哈希映射更合算。另一方面,對 collection 視圖進行迭代所需的時間與哈希表中的桶數成正比,所以如果特別注重迭代性能或內存使用,則不宜將期望的最大數量設置得過高。

此實現不是同步的。

由所有此類的“collection 視圖方法”所返回的迭代器都是快速失敗。

實現注意事項:此爲簡單的線性探頭 哈希表,如 Sedgewick 和 Knuth 原文示例中所述。該數組交替保持鍵和值(對於大型表來說,它比使用獨立組保持鍵和值更具優勢)。對於多數 JRE 實現和混合操作,此類比 HashMap(它使用鏈 而不使用線性探頭)能產生更好的性能。

源碼

成員以及構造方法:

    /**
     * The initial capacity used by the no-args constructor.
     * MUST be a power of two.  The value 32 corresponds to the
     * (specified) expected maximum size of 21, given a load factor
     * of 2/3.
     */
    private static final int DEFAULT_CAPACITY = 32;

    /**
     * The minimum capacity, used if a lower value is implicitly specified
     * by either of the constructors with arguments.  The value 4 corresponds
     * to an expected maximum size of 2, given a load factor of 2/3.
     * MUST be a power of two.
     */
    private static final int MINIMUM_CAPACITY = 4;

    /**
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<29.
     */
    private static final int MAXIMUM_CAPACITY = 1 << 29;

    /**
     * Constructs a new, empty identity hash map with a default expected
     * maximum size (21).
     */
    public IdentityHashMap() {
        init(DEFAULT_CAPACITY);
    }

    /**
     * Constructs a new, empty map with the specified expected maximum size.
     * Putting more than the expected number of key-value mappings into
     * the map may cause the internal data structure to grow, which may be
     * somewhat time-consuming.
     *
     * @param expectedMaxSize the expected maximum size of the map
     * @throws IllegalArgumentException if <tt>expectedMaxSize</tt> is negative
     */
    public IdentityHashMap(int expectedMaxSize) {
        if (expectedMaxSize < 0)
            throw new IllegalArgumentException("expectedMaxSize is negative: "
                                               + expectedMaxSize);
        init(capacity(expectedMaxSize));
    }

    /**
     * Returns the appropriate capacity for the specified expected maximum
     * size.  Returns the smallest power of two between MINIMUM_CAPACITY
     * and MAXIMUM_CAPACITY, inclusive, that is greater than
     * (3 * expectedMaxSize)/2, if such a number exists.  Otherwise
     * returns MAXIMUM_CAPACITY.  If (3 * expectedMaxSize)/2 is negative, it
     * is assumed that overflow has occurred, and MAXIMUM_CAPACITY is returned.
     */
    private int capacity(int expectedMaxSize) {
        // Compute min capacity for expectedMaxSize given a load factor of 2/3
        int minCapacity = (3 * expectedMaxSize)/2;

        // Compute the appropriate capacity
        int result;
        if (minCapacity > MAXIMUM_CAPACITY || minCapacity < 0) {
            result = MAXIMUM_CAPACITY;
        } else {
            result = MINIMUM_CAPACITY;
            while (result < minCapacity)
                result <<= 1;
        }
        return result;
    }

    /**
     * Initializes object to be an empty map with the specified initial
     * capacity, which is assumed to be a power of two between
     * MINIMUM_CAPACITY and MAXIMUM_CAPACITY inclusive.
     */
    private void init(int initCapacity) {
        // assert (initCapacity & -initCapacity) == initCapacity; // power of 2
        // assert initCapacity >= MINIMUM_CAPACITY;
        // assert initCapacity <= MAXIMUM_CAPACITY;
	// 閾值爲容量的2/3
        threshold = (initCapacity * 2)/3;
        // 內部數組的size爲容量的2倍,因爲IdentityHashMap將所有的key和value都存儲到Object[]數組table中,
        // 並且key和value相鄰存儲,因此map中每一對鍵值對都要佔用兩個位置。
        // 數組第一個位置存儲的是key,第二個位置存儲的是value。因此奇數位置處存儲的是key,偶數位置處存儲的是value。
        table = new Object[2 * initCapacity];
    }

    /**
     * Constructs a new identity hash map containing the keys-value mappings
     * in the specified map.
     *
     * @param m the map whose mappings are to be placed into this map
     * @throws NullPointerException if the specified map is null
     */
    public IdentityHashMap(Map<? extends K, ? extends V> m) {
        // Allow for a bit of growth
        this((int) ((1 + m.size()) * 1.1));
        putAll(m);
    }

put方法:

    public V put(K key, V value) {
    	// 若key爲null返回定義的nullkey
        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) {//這裏使用==判斷key是否是同一個key
            	i+1的位置上存着i位置上key的對應值
                V oldValue = (V) tab[i + 1];
                tab[i + 1] = value;
                return oldValue;
            }
            // 產生衝突,找到下一個爲null的位置
            // 獲取下一個鍵的位置 i+2
            i = nextKeyIndex(i, len);
        }
	// 數組中不存在這個鍵則新增
        modCount++;
        tab[i] = k;
        tab[i + 1] = value;
        // size+1後大於或等於閾值時擴容
        if (++size >= threshold)
            resize(len); // len == 2 * current capacity.
        return null;
    }
    /**
     * Value representing null keys inside tables.
     */
    private static final Object NULL_KEY = new Object();

    /**
     * Use NULL_KEY for key if it is null.
     */
    private static Object maskNull(Object key) {
        return (key == null ? NULL_KEY : key);
    }
    /**
     * Returns index for Object x.
     */
    private static int hash(Object x, int length) {
    	// 使用System.identityHashCode來確定對象的哈希碼,該方法返回對象的地址。
        int h = System.identityHashCode(x);
        // Multiply by -127, and left-shift to use least bit as part of hash
        return ((h << 1) - (h << 8)) & (length - 1);
    }
        /**
     * Circularly traverses table of size len.
     */
    private static int nextKeyIndex(int i, int len) {
        return (i + 2 < len ? i + 2 : 0);
    }

擴容:

    private void resize(int newCapacity) {
        // assert (newCapacity & -newCapacity) == newCapacity; // power of 2
        int newLength = newCapacity * 2;

        Object[] oldTable = table;
        int oldLength = oldTable.length;
        if (oldLength == 2*MAXIMUM_CAPACITY) { // can't expand any further
             // 若當前數組容量已經是最大
            if (threshold == MAXIMUM_CAPACITY-1)
            	// 閾值最大,報錯
                throw new IllegalStateException("Capacity exhausted.");
            // 擴大閾值
            threshold = MAXIMUM_CAPACITY-1;  // Gigantic map!
            return;
        }
        // 容量已經夠用了 返回
        if (oldLength >= newLength)
            return;

        Object[] newTable = new Object[newLength];
        // newLength前邊已經乘2
        threshold = newLength / 3;

        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;
                // 重新計算hash值
                int i = hash(key, newLength);
                while (newTable[i] != null)
                    i = nextKeyIndex(i, newLength);
                newTable[i] = key;
                newTable[i + 1] = value;
            }
        }
        table = newTable;
    }

get方法:

    public V get(Object key) {
    	// nullkey判斷
        Object k = maskNull(key);
        Object[] tab = table;
        int len = tab.length;
        // 計算位置
        int i = hash(k, len);
        while (true) {
            // 一直到找到該key(key地址相等)或者不存在該key(位置爲null)時返回。
            Object item = tab[i];
            if (item == k)
                return (V) tab[i + 1];
            if (item == null)
                return null;
            // put時發生衝突會放到之後第一個爲null的位置上
            i = nextKeyIndex(i, len);
        }
    }

remove方法:

    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--;
                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);
        }

    }
    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) ) {
            // The following test triggers if the item at slot i (which
            // hashes to be at slot r) should take the spot vacated by d.
            // If so, we swap it in, and then continue with d now at the
            // newly vacated i.  This process will terminate when we hit
            // the null slot at the end of this run.
            // The test is messy because we are using a circular table.
            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;
            }
        }
    }

與HashMap的比較

  • 比較key時是“引用相等”。
  • 支持null
  • 所有的key和value都存儲到Object[]數組table中,並且key和value相鄰存儲,當出現哈希衝突時,會往下遍歷數組,直到找到一個空閒的位置。
  • 加載因子爲2/3
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章