一个HashMap源码问题

一个问题

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

你们能够看下,上面的代码输出是什么?我稍后公布答案。java

源码分析

HashMap的get方法源码以下(增长本身的注释):node

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值是否一致code

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

看了上述源码分析以后,咱们公布答案:get

null
1

最终的差别就是源码

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

这段代码,至关于 Objects.equals(key, k)hash

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

至关于比较new Integer(1)new Long(1L),咱们知道它们是两个不一样的对象,因此结果确定不相等。因此key是1L的时候,结果是nullclass

结论

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