HashMap源码(八)

get方法

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

点击getNode方法进入如下代码:

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) {     //判断对应的index是否有元素
        if (first.hash == hash &&  //定位到index,判断该元素的key是否相同,用双等号、equals来判断
            ((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 {
                //遍历链表找到给定key对应的节点
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))     
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}

步骤

1)对key取hash值。
2)将hash值与(n-1)做与运算得到index
3)如果数组中该index位置为null,则直接返回null
4)如果数组中该index位置的元素的key和我传入的key相等(满足双等号和equals一个即可),则返回给元素。否则遍历链表或红黑树。
5)如果该index位置的元素属于红黑树节点,则走红黑树返回该节点。
6)如果该index位置的元素属于链表节点,则遍历链表,与步骤4)中的检索方式一样。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值