HashMap源码(jdk 1.8)- 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))))
	// 1、待查找的数据为对应桶的首节点
            return first;
        if ((e = first.next) != null) {
	// 2、待查找的数据不为对应桶的首节点
            if (first instanceof TreeNode)
		// 2.1 节点为红黑树,从红黑树中获取对应数据
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            do {
		// 2.2 节点为链表节点,遍历链表,从中获取对应数据
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}

问题

  1. 获取数据的大致流程?

(1)计算数据在桶中的位置((tab.length- 1) & hash(key)

(2)通过hash值和key值判断待查找的数据是否在对应桶的首节点,如果在,则返回对应节点数据;否则判断桶首节点的类型。如果节点为红黑树,从红黑树中获取对应数据;如果节点为链表节点,遍历链表,从中获取对应数据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值