自己分析一下HashMap源碼

  • HashMap關鍵結構
public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
    static final int MAXIMUM_CAPACITY = 1 << 30;
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    transient Node<K,V>[] table;   //構建哈希所用的數組
    transient int size;
    transient int modCount;//修改次數

    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        ... ...

    }
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    /**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }
    ... ...
    ... ...
}
  • Node《K,V》 table就是Node數組(Node是HashMap的內部類,實現自Map.Entry《K,V》;成員屬性有key,value分別存鍵和值;Node類型的next成員,在產生衝突時形成鏈表存入一個指定槽中),向HashMap裏添加的一對新的鍵值對,就是向這個table即添加一個新的Node元素。
  • 構建以及插入的步驟:計算得到鍵值對中鍵的hash碼(HashMap中的hash()方法),再經過計算(i = (n - 1) & hash)得到這個新的鍵值對作爲table數組中的下標,如果這個位置bucket(一般稱數組中的每個位置爲槽)已經有了元素,說明鍵值對中鍵的hash碼和新插入鍵值對中鍵的hash碼,這時判斷這兩個鍵是否相同(具體取決於鍵的類型K的equals方法和 == ),相同則新鍵值對替換舊的鍵值對並返回舊的鍵值對中的value。不同則,使用鏈表的形式,將新的Node追加到原有Node後面。最後兩種情況都要modcount修改次數加1.
  • get的步驟:首先是獲取你想要的Node,有了Node返會Node.value直接就是你想要的值了。
    getNode的步驟是:由hashCode經過計算得到在數組中的位置index,取出這個index對應槽中存的Node節點,如果有衝突的話該Node節點後面還有接Node節點形成鏈表,如果沒有衝突的話,就只有這個Node節點。從第一個節點向後遍歷,判斷這一個個節點哪個的key和用戶傳進來的key相等(取決於key類型的equals方法和 ==),只有節點的hashCode和用戶傳來key的hashCode相等並且兩者key值相等,纔是真正要返回的節點。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章