HashMap原理学习记录

109 阅读3分钟

HashTable HashMap TreeMap

  • HashTable 同步,不支持null键和值,性能开销比较大

  • HashMap

不同步,支持null键和值,数组+链表实现

  • TreeMap 红黑树实现,有顺序的map

HashMap源码分析

image.png

Node,存放hash,key,value,next

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

table

transient Node<K,V>[] table;

hash值计算:

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

hash索引计算:

p = tab[i = (n - 1) & hash]

put操作

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

/**
 * Implements Map.put and related methods
 *
 * @param hash key
 * @param key
 * @param value
 * @param onlyIfAbsent true如果值已经存在则不改变
 * @param evict fasle table处于创造模式
 * @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;
    // hash table为空,设置默认大小
    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;
        // 第一个Node的hash和key值和插入的一致,直接取出
        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 {
            // hash值不一致,遍历链表,如果为空,则插入
            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;
            }
        }
        // 存在key
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            // 如果需要更新旧的值
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;  // HashMap被修改的次数
    
    // key-map数量大于阈值,扩容,初始threshold=16,
    if (++size > threshold)
        resize();
    // 插入回调
    afterNodeInsertion(evict);
    return null;
}

get操作

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;
    table不为空&& 链表第一个值不为空
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
        // 第一个节点hash,key一致
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        // 第一个节点的next不为空
        if ((e = first.next) != null) {
            // LinkedHashMap
            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;
}

Resize操作

final Node<K,V>[] resize() {
    Node<K,V>[] oldTab = table;
    // 当前hash桶容量
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    // 当前key-map阈值
    int oldThr = threshold;
    // 新的容量,新的阈值
    int newCap, newThr = 0;
    // 老的table的容量大于0
    if (oldCap > 0) {
        // 大于默认最大容量
        if (oldCap >= MAXIMUM_CAPACITY) {
            // 容量阈值设置为2^31-1
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        // 新的容量为旧的容量的2倍
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
            // 阈值也设置为两倍
            newThr = oldThr << 1; // double threshold
    }
    // 旧的阈值大于0,标示已经出初始化过了,直接设置新的容量为旧的阈值
    else if (oldThr > 0) // initial capacity was placed in threshold
        newCap = oldThr;
    else {               // zero initial threshold signifies using defaults
        // 否则初始化容量和阈值
        newCap = DEFAULT_INITIAL_CAPACITY;
        // 初始阈值=加载因子*初始容量
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    // 如果新的阈值==0
    if (newThr == 0) {
        // 重新计算阈值
        float ft = (float)newCap * loadFactor;
        newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                  (int)ft : Integer.MAX_VALUE);
    }
    threshold = newThr;
    @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    // 创建新的hash桶
    table = newTab;
    // 写入原来的数据
    if (oldTab != null) {
        // 遍历旧的hash桶
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            // 如果对应的链表不为空
            if ((e = oldTab[j]) != null) {
                // 将旧的链表置空
                oldTab[j] = null;
                // 如果链表只有一个元素
                if (e.next == null)
                    // 直接丢入新的hash桶中,索引为hash & (新的hash桶容量-1)
                    newTab[e.hash & (newCap - 1)] = e;
                else if (e instanceof TreeNode)
                    // 链表已经转换成了树
                    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                else { // preserve order
                    // 低位头节点,低位尾节点
                    Node<K,V> loHead = null, loTail = null;
                    // 高位头节点,高位尾节点
                    Node<K,V> hiHead = null, hiTail = null;
                    // 临时节点
                    Node<K,V> next;
                    do {
                        next = e.next;
                        // 应该存放在低位
                        if ((e.hash & oldCap) == 0) {
                            if (loTail == null)
                                loHead = e;
                            else
                                loTail.next = e;
                            loTail = e;
                        }
                        else {
                            // 存放在高位
                            if (hiTail == null)
                                hiHead = e;
                            else
                                hiTail.next = e;
                            hiTail = e;
                        }
                    } while ((e = next) != null);
                    // 低位节点赋值
                    if (loTail != null) {
                        loTail.next = null;
                        newTab[j] = loHead;
                    }
                    // 高位节点赋值
                    if (hiTail != null) {
                        hiTail.next = null;
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    return newTab;
}