gpt4 book ai didi

java - java.utils.HashMap 中的 Node.equals 方法

转载 作者:行者123 更新时间:2023-12-02 01:41:53 24 4
gpt4 key购买 nike

Hashmap 中的静态类 Node 有一个 equals 方法,用于将此 Node 对象与作为参数传递的 Node 对象进行比较。

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;
}
}

看一下将对象 o 分配给新的 Map.Entry 对象 e 的行。键和值的比较可以通过对象 o 本身来完成。为什么先复制到对象e然后再比较呢?对象 o 没有以任何方式被修改。

最佳答案

线路Map.Entry<?,?> e = (Map.Entry<?,?>)o;不会分配给新的 Map.Entry 对象,它仅强制转换 oEntry对象,允许使用 getKey()getValue()与当前比较所需的方法 Entry对象

o 上唯一可用的方法详细信息请参见 java.lang.Object

关于java - java.utils.HashMap 中的 Node.equals 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54364957/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com