Java HashMap中get方法的原理

  1. 首先向get()方法中传递一个key

  2. 在get()方法中调用hash(key),如果key!=null,返回该key的哈希值hash = key.hashCode()^ (h >>> 16),否则返回hash=0

  3. 在get()方法中调用getNode(hash,key)方法,获取该key的节点,并返回value

  4. getNode()方法中首先要判断Hashtable是否为空且table长度大于0且该hash值对应的table元素不为空,条件成立则判断该节点的哈希值是否等于hash,依次遍历该链表或红黑树,查找key==node.key?返回查找到的节点的value 

// JDK源码 
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;
		//判断hashtable是否为空,key对应的tab[ ]是否为空
        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;
			//判断下一个节点是否为空
            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;
    }

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值