HashMap源码解读

HashMap:HashMap是最常用的Map结构。具体的实现是以一个Node<K,V>为的静态内部类的数组来实现,每个Node可能是Node的链表或红黑树结构。初始化容量为16或不小于自定义initialCapacity最小二进制数或最大容量,从JDK8之后,小于8个元素是链表存储结构。大于8个并且整个table的容量大于64个之后变成了红黑树结构。HashMap每次增加容量将原数组变成之前的2倍。

1、如何保证每次每次获得不小于cap的最小二进制数    

static final int tableSizeFor(int cap) {
    int n = cap - 1;//减1保证cap已经是2的倍数,此时不减1的话,后面移位后n将变成cap的2倍
    n |= n >>> 1;//先对n进行右移操作后,在与n进行或运算
    n |= n >>> 2;
    n |= n >>> 4;
    n |= n >>> 8;
    n |= n >>> 16;//右移保证该数从为1的最高位开始到低位全是1
    return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;//判断n是否大于等于最大容量,不大于时n+1即为大于cap的最小二进制数
}
 

2、hash的实现

 

static final int hash(Object key) {
    int h;//取高15位与原值做与运算,结果保留了高位和低位的信息,以此来减少hash碰撞
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

3、HashMap的put实现:

 

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)//新分配table
        n = (tab = resize()).length;
    if ((p = tab[i = (n - 1) & hash]) == null)// table里对应下标这个node为空,下标计算为key的hash值与table长度与,即取低位
        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))))//如果该node不为空,比较key的hash值相等并且key值是否值相等
            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);//找到下一个为空的node地方新插入node
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);// 如果某个节点往后超过6个节点才找到空node,则对改tab进行树化
                    break;
                }
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))//找到对应节点
                    break;
                p = e;//循环下一个node
            }
        }
        if (e != null) { // existing mapping for key//替换改node的value值
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;//
    if (++size > threshold) //重新分配HasMap的table容量,从这里和Hashmap的构造函数可以看出直接设置初始容量为数据条数,可以防止hashmap重新分配table空间
        resize();
    afterNodeInsertion(evict);
    return null;
}

4、resize方法的实现:

 

final Node<K,V>[] resize() {
    Node<K,V>[] oldTab = table;//获取之前的数据
    int oldCap = (oldTab == null) ? 0 : oldTab.length;//capacity
    int oldThr = threshold;//capacity*loadFactory,下次resize的阀值
    int newCap, newThr = 0;
    if (oldCap > 0) {
        if (oldCap >= MAXIMUM_CAPACITY) {//如果已有的数据超过最大的容量限制,则table不做修改
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)//如果以已有数据量*2之后小于最大容量并且已有数据量大于等于初始容量时
            newThr = oldThr << 1; // double threshold//新的table的容量为之前的两倍,新table的阀值为之前的两倍
    }
    else if (oldThr > 0) // initial capacity was placed in threshold
        newCap = oldThr;
    else {               // zero initial threshold signifies using defaults
        newCap = DEFAULT_INITIAL_CAPACITY;//初始容量  16
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//初始阀值 默认平衡因子0.75
    }
    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];//新分配table
    table = newTab;
    if (oldTab != null) {//将以前的table数据写入新的table中
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;
                if (e.next == null)//如果这个节点的next为空,重写计算该节点在新table里的位置并放进去
                    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 {//table[j]开始
                        next = e.next;
                        if ((e.hash & oldCap) == 0) {//记录下原下标为0的一组node
                            if (loTail == null)
                                loHead = e;
                            else
                                loTail.next = e;
                            loTail = e;
                        }
                        else {//记录原下标不为0的一组node
                            if (hiTail == null)
                                hiHead = e;
                            else
                                hiTail.next = e;
                            hiTail = e;
                        }
                    } while ((e = next) != null);
                    if (loTail != null) {// 如果oldtab[j]开始找到的是原下标为0一组node,放入新table的相同位置
                        loTail.next = null;
                        newTab[j] = loHead;
                    }
                    if (hiTail != null) {// 如果改node的下标不为0,放入新table的对应位置
                        hiTail.next = null;
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    return newTab;
}

5、treeifyBin方法:

 

final void treeifyBin(Node<K,V>[] tab, int hash) {
    int n, index; Node<K,V> e;
    if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)//如果table的长度没达到最小树形界限,不做树型化调用resize
        resize();
    else if ((e = tab[index = (n - 1) & hash]) != null) {//如果对应node不为空
        TreeNode<K,V> hd = null, tl = null;
        do {// 找出该下标值相同的一组node
            TreeNode<K,V> p = replacementTreeNode(e, null);//替换该hash值的节点为树型节点
            if (tl == null)
                hd = p;
            else {
                p.prev = tl;
                tl.next = p;
            }
            tl = p;
        } while ((e = e.next) != null);
        if ((tab[index] = hd) != null)
            hd.treeify(tab);//如果该节点不为空,对该节点做树化
    }
}

6、treeify方法:

 

final void treeify(Node<K,V>[] tab) {//将该node树化成红黑树
    TreeNode<K,V> root = null;
    for (TreeNode<K,V> x = this, next; x != null; x = next) {
        next = (TreeNode<K,V>)x.next;
        x.left = x.right = null;
        if (root == null) {//第一个节点为黑节点
            x.parent = null;
            x.red = false;
            root = x;
        }
        else {
            K k = x.key;
            int h = x.hash;
            Class<?> kc = null;
            for (TreeNode<K,V> p = root;;) {
                int dir, ph;
                K pk = p.key;
                if ((ph = p.hash) > h)//如果该node的hash值大于根节点的hash值,dir=-1
                    dir = -1;
                else if (ph < h)
                    dir = 1;
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0)
                    dir = tieBreakOrder(k, pk);

                TreeNode<K,V> xp = p;
                if ((p = (dir <= 0) ? p.left : p.right) == null) {//dir小于等于0时,根node的左孩子空或dir大于0,根node的右孩子空
                    x.parent = xp;// 设置当前节点的父node为root
                    if (dir <= 0)// 插入左孩子
                        xp.left = x;
                    else
                        xp.right = x;
                    root = balanceInsertion(root, x);//平衡插入
                    break;
                }
            }
        }
    }
    moveRootToFront(tab, root);//将root移到最前
}

7、getNode方法:

 

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 {//没达到该节点树化条件,即链表长度没超过64个node,依次查找链表
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值