LoginSignup
1
0

More than 1 year has passed since last update.

JavaのHashMapの中身を覗いてみた

Last updated at Posted at 2020-07-05

JavaのHashMapのソースコードを読んで、hashのキーの比較が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;                            // 内部配列
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {                                // 内部配列の(hashCode/配列の長さの剰余)番目に収納されている要素(LinkedListの最初のNode)
            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 {                                                                 // LinkedListを順々に探索していく
                    if (e.hash == hash &&                                            // hashCodeが異なったら次のNodeへ(optimization目的)      
                        ((k = e.key) == key || (key != null && key.equals(k))))      // ここでequals()で比較!!!!!!
                        return e;
                } while ((e = e.next) != null);     
            }
        }
        return null;
    } 

探索中のオブジェクトと探索中のLinkedListの各Nodeの持つkeyのオブジェクトを、それぞれのequals()を用いて同意性比較していることが確認できた。

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0