A problem

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

If you look at it, what’s the output of the code above? I’ll give you the answer later.

Source code analysis

The source code for the Get method of HashMap is as follows (with its own comments) :

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; // If map is not empty if ((TAB = table)! = null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) ! = null) {// If the value is found directly from the key passed in, // 1) Compare the hash value of the passed key with that of the node found in the map. // 2) Compare the hash value of the passed key with that of the node found in the map. If (first.hash == hash && // always check first node ((k = first.key) == key || (key ! = null && key.equals(k)))) return first; If ((e = first.next)); // If (e = first.next); If (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreenode (hash, key); / / if it is a common list, the list traversal search do {the if (e.h ash = = hash && ((k = e.k ey) = = key | | (key! = null && key.equals(k)))) return e; } while ((e = e.next) ! = null); } // Return null; }

If the hash value of the passed key matches the node in the map (let’s just say there is something in the hash table), then two judgments need to be made.

1) Compare whether the hash value of the passed key is consistent with that of the node found in the corresponding position in the map

2) == Compare whether the passed key object is equal to the key object of the node found in the corresponding position in the map ==

After looking at the above source code analysis, we publish the answer:

null
1

The final difference is

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

Object.equals (key, k)

What we’re comparing here is the key of the object stored in the map, named k, and the key passed to the map by the get method, named key.

This is equivalent to comparing new Integer(1) with new Long(1L). We know that they are two different objects, so the result must not be equal. So when the key is 1 liter, it’s going to be null.

conclusion

When Map obtained the value, the key type did not match, and the value could not be obtained.