jdk1.8HashMap源码分析

265 阅读1分钟

jdk1.8采用数组+链表+红黑树的结构来实现。内部类主要有Node单向链表、KeySet类 values、EntrySet、HashIterator、KeyIterator、ValueIterator、EntryIterator 、HashMapSpliterator、KeySpliterator、ValueSpliterator、EntrySpliterator、 TreeNode红黑树结构

hashMap结构:

单向链表结构

红黑树结构

//put的核心方法

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {

//如果table为空就resize()扩容,返回table长度给n

    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
    else {
        Node<K,V> e; K k;
        //如果链表第一个元素或树的根的key与要插入的数元素重复,覆盖旧值
        if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        //如果是tree,则调用putTreeVal
        else if (p instanceof HashMap.TreeNode)
            e = ((HashMap.TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        //如果只是hash冲突,并且是链表,则进入esle
        else {
            //遍历链表 找到合适的处理方式 1插入新节点 2覆盖旧值
            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;
                }
                //如果链表中有一个节点key和插入的key重复,则跳出循环。此时的e指向这个key重复的节点
                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;
}

get的核心方法getNode