[Java] I took a peek inside the Java HashMap

1 minute read

Read the Java HashMap source codeandreadthe`hashIhaveconfirmedthatthekeycomparisonisdonewithequals().

    /**
     * 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) {/ (hashCode/remainder of array length) element of the internal array (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 LinkedList in order
                    if (e.hash == hash && // If hashCode is different, go to next node (for optimization purpose)
                        ((k = e.key) == key || (key != null && key.equals(k)))) // compare with equals() here!!!!!!
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

It was confirmed that the object being searched and the object of the key of each Node of the LinkedList being searched were compared for agreement by using their equals().

Reference