HashMap的源码分析(jdk1.8)

jdk1.8后,HashMap的底层实现由“数组+链表”转换成了“Node【】数组+链表+红黑树的形式”。

HashMap中的几个关键点

1.转为红黑树后,链表的结构依然存在,通过next属性维持。
2.红黑树中,叶子结点也可能有next结点。
3.进行红黑树查找时,会反复判断hash值和key值,如果小于则向左遍历,大于向右遍历。
4.红黑树中有一个dir属性(int),存储的值表明向左还是向右遍历。

HashMap中的hash值计算

在HashMap中,hash值的计算是通过得到key.hashcode并与其自身高16位进行计算得到。这样的话,可以使数据分布均匀,当我们使用hash算法时,可以很快得到我们想要的位置索引。并且,进行位运算的效率高于进行模运算的效率。

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

int index = (n - 1) & hash;

HashMap的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;
    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;   
}

HashMap查找数组索引时,会首先判断头结点的hash值和key值与目标结点是否匹配,匹配则返回。否则向下遍历,遍历过程中会判断下一个结点是红黑树(调用getTreeNode)还是链表。并比较hash值和key值,匹配则返回,否则返回null。

HashMap的find方法

final TreeNode<K,V> find(int h, Object k, Class<?> kc) {    
    TreeNode<K,V> p = this; 
    do {
        int ph, dir; K pk;
        TreeNode<K,V> pl = p.left, pr = p.right, q;
        if ((ph = p.hash) > h) 
            p = pl;
        else if (ph < h)    
            p = pr; 
        else if ((pk = p.key) == k || (k != null && k.equals(pk))) 
            return p;
        else if (pl == null)    
            p = pr; 
        else if (pr == null)   
            p = pl;
        else if ((kc != null ||
                  (kc = comparableClassFor(k)) != null) && 
                 (dir = compareComparables(kc, k, pk)) != 0)//k<pk则dir<0, k>pk则dir>0
            p = (dir < 0) ? pl : pr;    
        else if ((q = pr.find(h, k, kc)) != null)   
            return q;
        else
            p = pl; 
    } while (p != null);
    return null;
}

首先将调用此方法的节点进行赋值,在该方法中,通过比较目标结点与该结点的hash值选择向左或者向右遍历。如果传入的key的类实现了Comparable接口,则可通过compareComparables方法进行比较赋值给dir,并判断dir的大小进行向左或者向右遍历。

HashMap的put方法

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}
 
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)
                        treeifyBin(tab, hash);
                    break;
                }
                if (e.hash == hash && 
                    ((k = e.key) == key || (key != null && key.equals(k)))) 
                    break;
                p = e; 
            }
        }
        if (e != null) { 
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e); 
            return oldValue;
        }
    }
    ++modCount;
    if (++size > threshold) 
        resize();
    afterNodeInsertion(evict);  
    return null;
}

通过hash值获得索引,首先将索引位置的结点赋值给p,并判断头结点是否为null,为null则创建一个新的结点。如果不为null,则判断p结点(暂时为头结点)的hash值和key值是否与传入的值匹配,匹配则将p结点赋值给e;是红黑树则调用putTreeVal方法;没有匹配上的话,则遍历该链表。如果p.next为null,则创建一个新的结点。在创建结点后,会判断节点数是否超过8个,超过8个转换成红黑树。在遍历链表后,匹配上的话结束循环,并讲p指向下一个结点。

HashMap的putTreeVal方法


final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
                               int h, K k, V v) {
    Class<?> kc = null;
    boolean searched = false;
    TreeNode<K,V> root = (parent != null) ? root() : this;  
    for (TreeNode<K,V> p = root;;) {    
        int dir, ph; K pk;
        if ((ph = p.hash) > h)  
            dir = -1;	
        else if (ph < h)   
            dir = 1;	
  
        else if ((pk = p.key) == k || (k != null && k.equals(pk)))  
            return p;
 
        else if ((kc == null &&
                  (kc = comparableClassFor(k)) == null) ||
                 (dir = compareComparables(kc, k, pk)) == 0) { 
            if (!searched) {   
                TreeNode<K,V> q, ch;
                searched = true;
            
                if (((ch = p.left) != null &&
                     (q = ch.find(h, k, kc)) != null) ||
                    ((ch = p.right) != null &&
                     (q = ch.find(h, k, kc)) != null))  
                    return q;
            }
 
            dir = tieBreakOrder(k, pk);
        }
 
        TreeNode<K,V> xp = p;  
     
        if ((p = (dir <= 0) ? p.left : p.right) == null) {  
        
            Node<K,V> xpn = xp.next;    
        
            TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);   
            if (dir <= 0)  
                xp.left = x;
            else       
                xp.right = x;
            xp.next = x;   
            x.parent = x.prev = xp;
           
            if (xpn != null)    
                ((TreeNode<K,V>)xpn).prev = x;
            moveRootToFront(tab, balanceInsertion(root, x)); 
            return null;
        }
    }
}
  1. 首先查找根结点,并复制给p(索引位置头结点,不一定是根结点)。
  2. 遍历红黑树,传入的hash值小于p.hash则向左遍历,否则向右遍历。
  3. 传入的hash和key值匹配p的话,返回p。
  4. 如果传入的key的类没有实现comparable接口,或者k和p的key值相等。
  5. 第一次可以进入,并调用p的左或者右结点的find方法,如果找到返回。
  6. 否则调用tieBreakOrder方法判断向左还是向右遍历。
  7. 接着继续向左或者向右遍历,当p为null时,放入该新结点。并进行平衡性调整。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值