Read the Java HashMap Source Code (https://github.com/AdoptOpenJDK/openjdk-jdk8u/blob/master/jdk/src/share/classes/java/util/HashMap.java) and read the hash Confirmed that the key comparison is done with equals ()
.
/**
* 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; //Internal array
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) { //Of the internal array(hashCode/Array length remainder)The second stored element(First Node of LinkedList)
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 { //Search the Linked List one by one
if (e.hash == hash && //If the hashCode is different, go to the next Node(optimization purpose)
((k = e.key) == key || (key != null && key.equals(k)))) //Here equals()Compare with!!!!!!
return e;
} while ((e = e.next) != null);
}
}
return null;
}
It was confirmed that the object under search and the object with the key of each Node of the LinkedList under search are compared for consent using their respective equals ().
tab [(n -1) & hash]
is (hashCode / remainder of array length)Recommended Posts