天上飞的云传奇 2021-10-12 19:05 采纳率: 83.3%
浏览 17

HashMap node元素中的hashcode(),equals()方法什么时候调用?

源代码

static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }


自定义类没实现直接调用的是Object类的Hashcode和equals啊,node中的什么时候调用了?

  • 写回答

2条回答 默认 最新

  • Tomshidi 2021-10-12 20:09
    关注

    会在所有需要定位Node元素的位置调用,HashMap中自己又封装了一层,叫static final int hash(Object key)

    img

    img

    评论

报告相同问题?

问题事件

  • 创建了问题 10月12日