一个HashMap源码问题

569 阅读2分钟

一个问题

Map<Integer, Integer> map = new HashMap<>();
resMap.put(1, 1);
System.out.println(map.get(1L));
System.out.println(map.get(1));

大家可以看下,上面的代码输出是什么?我稍后公布答案。

源码分析

HashMap的get方法源码如下(增加自己的注释):


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

/**
 * Implements Map.get and related methods.
 *
 * @param hash hash for key
 * @param key the key
 * @return the node, or null if none
 */
final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    // 如果map不为空
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
        // 如果直接通过传进来的key找到了值,直接返回
        // 1)比较传进来key的hash值和在map中对应位置找到的结点的hash值是否一致
        // 2)比较传进来的key对象和在map中对应位置找到的结点的key对象(object)是否相等
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        // 如果通过hash找到的结点的下一个节点不为空,说明是链表
        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);
        }
    }
    // 上述都不满足,返回null
    return null;
}

如果传的key对应的hash值,能够匹配到map中的结点(只能说hash表(map)中这个位置有东西),还需要进行下面两个判断。

1)比较传进来key的hash值和在map中对应位置找到的结点的hash值是否一致

2)==比较传进来的key对象和在map中对应位置找到的结点的key对象(object)是否相等==

看了上述源码分析之后,我们公布答案:

null
1

最终的差异就是

(k = first.key) == key || (key != null && key.equals(k))

这段代码,相当于 Objects.equals(key, k)

这里比较的是,map 中存储的对象的key,命名为k,以及get方法传给map的key,命名为key。

相当于比较new Integer(1)new Long(1L),我们知道它们是两个不同的对象,所以结果肯定不相等。所以key是1L的时候,结果是null

结论

Map 获取值的时候,key类型不匹配,获取不到value。