e.hash == hash && ( (k = e.key) == key || (key != null && key.equals(k)) )

记住这个定理吧:

equal objects must have equal hash codes.


首先:java.lang.Object.hashCode() 是三条约定是

1、多次运行 hashCode(),其值必须总是一致的(前提:1、 equals() 中用到的信息没发生变化 2、在同一次 execution 中)

2、obj1.equals(obj2) == true,则必须  obj1.hashCode() == obj1.hashCode() 总是 true

3、obj1.equals(obj2) == false,则 obj1.hashCode() == obj1.hashCode()  最好 false可怜 

        这是因为 HashMap.containsKey(),HashMap.put() 时

        a:由于 hash 不同,则直接就不尝试了(好。这样效率高啊

        b:“两把刷子程序员” 把 hash 弄成相同的(equals()不同,hashCode()相同),还得向下尝试 equals() (不好


像我这种心细的 2B 青年,肯定会问(既然 equals() 对 hashCode() 提了这么多要求;那么,hashCode() 可怜巴巴的提了点什么要求呢 )

4、obj1.hashCode() == obj1.hashCode()  是 true,则:obj1.equals(obj2) 必须是 true 嘛?

        不必须是true,但最好是true。obj1.equals(obj2) 为 false 也行,这时(equals() false,hashCode() true),根据3(equals() false,则 hashCode() 最好 false),这不是好的情况

5、obj1.hashCode() == obj1.hashCode()  是 false,则:obj1.equals(obj2) 必须是 false 嘛?

        是的。如若 obj1.equals(obj2) 为true,根据2(equals() true,hashCode() 必须true),那不又返过来使得 hashCode()又true了嘛


HashMap中,如何决定 某个 key 已经存在?

必须满足两条,而且是按这个顺序来的

1、key.hashCode() == keyX.hashCode()

2、key.equals(keyX)

containsKey(Object key) 是如下实现的

    /**
     * Returns <tt>true</tt> if this map contains a mapping for the
     * specified key.
     *
     * @param   key   The key whose presence in this map is to be tested
     * @return <tt>true</tt> if this map contains a mapping for the specified
     * key.
     */
    public boolean containsKey(Object key) {
        return getEntry(key) != null;
    }

    /**
     * Returns the entry associated with the specified key in the
     * HashMap.  Returns null if the HashMap contains no mapping
     * for the key.
     */
    final Entry<K,V> getEntry(Object key) {
        int hash = (key == null) ? 0 : hash(key.hashCode());
        // 注意:
        // 1、hash必须是相同的
        // hash 通过 hash(key.hashCode())而得到。可以认为 只有参数相同 方法hash()才会返回相同值。即 hashCode() 是相同的
        // 2、key.equals(k)
        for (Entry<K,V> e = table[indexFor(hash, table.length)];
             e != null;
             e = e.next) {
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k))))
                return e;
        }
        return null;
    }


put(K key, V value)()是如下实现的

    /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key.hashCode());
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            //注意:
            // 1. hash必须相同
            // 2、key.equals(k)
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }




这段代码是Java中HashMap的putVal方法的实现,用于向HashMap中插入键值对。下面是对代码的注释和说明: ```java final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; // 存储桶数组 Node<K,V> p; // 当前节点 int n, i; // 存储桶数组长度和索引 // 如果table为空或长度为0,则进行扩容 if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; // 计算出在存储桶数组中的索引 if ((p = tab[i = (n - 1) & hash]) == null) // 如果索引位置为空,则直接插入新节点 tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) // 如果当前节点的哈希值和键与要插入的键值对相同,则直接替换值 e = p; else if (p instanceof TreeNode) // 如果当前节点是红黑树节点,则调用红黑树节点的插入方法 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { // 遍历链表,查找是否已存在相同键的节点 for (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) { // 如果链表已到末尾,则在末尾插入新节点 p.next = newNode(hash, key, value, null); if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st // 如果链表长度达到阈值,将链表转换为红黑树 treeifyBin(tab, hash); break; } if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) // 如果找到相同键的节点,则退出循环 break; p = e; } } if (e != null) { // 存在相同键的节点 V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) // 如果不仅仅是替换已存在的键值对,或者旧值为空,则替换旧值 e.value = value; afterNodeAccess(e); return oldValue; } } // 更新修改次数和元素个数,并进行扩容或后续处理 ++modCount; if (++size > threshold) resize(); afterNodeInsertion(evict); return null; } ``` 该方法的主要功能是将键值对插入到HashMap中。它首先根据哈希值计算出键值对在存储桶数组中的索引,然后根据索引定位到对应的节点。 如果节点为空,则直接在该位置插入新节点;如果节点的哈希值和键与要插入的键值对相同,则直接替换节点的值;如果节点是红黑树节点,则调用红黑树节点的插入方法;如果节点是链表节点,则遍历链表查找是否已存在相同键的节点,如果找到则替换值,如果未找到则在链表末尾插入新节点。 插入完成后,更新HashMap的修改次数和元素个数,并根据需要进行扩容或后续处理。 希望对你有所帮助!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值