java源码之HashMap的get

java源码之HashMap的get

今天面试了一天本来不想写了,但想想自己立下的flag,还是继续写。今天面试的时候被面试官询问hashMap的get方法底层源码是什么样子的,没看过,遂晚上回来看看。

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

主要就是这个getNode方法,我们看看入参,因为get方法传的是key值,hash就是key值经过hash算法得到的值,key即要找的键。我们看下table是什么

/**
     * The table, initialized on first use, and resized as
     * necessary. When allocated, length is always a power of two.
     * (We also tolerate length zero in some operations to allow
     * bootstrapping mechanics that are currently not needed.)
     */
    transient Node<K,V>[] table;

table我们看到其实就是一个Node的对象集合,并且他的长度总为2的幂次,也允许为0。我们看看Node对象。这里就放构造方法和参数了。

final int hash;
final K key;
V value;
Node<K,V> next;

Node(int hash, K key, V value, Node<K,V> next) {
    this.hash = hash;
    this.key = key;
    this.value = value;
    this.next = next;
}

我们看到Node其实就是一个单向链表。
那么到此为止我们对hashMap的存储结构应该就有了初步的认知。table数组里面存放了Node节点,同时Node节点本身是一个链表结构。
(first = tab[(n - 1) & hash])我们可以看到,其实是通过(n - 1) & hash来确定这个元素存放的下标,因为存放的时候也是按照(n - 1) & hash来存的,至于为什么,等我再琢磨琢磨。我们通过这个方式找到下标后,因为数组里面存的也是链表,所以就需要遍历链表找到对应的值。但是链表长度超过8会变成红黑树,我们这里也不讨论,等我琢磨透了再来写博客。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值