提问人:Amit Agrawal 提问时间:1/25/2019 更新时间:1/25/2019 访问量:795
java.utils.HashMap 中的 Node.equals 方法
Node.equals method in java.utils.HashMap
问:
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 未以任何方式被修改。
答:
1赞
Ben R.
1/25/2019
#1
因为为了访问方法 和 ,它需要被强制转换为 。这就是那条线所做的一切。getKey()
getValue()
Map.Entry
1赞
azro
1/25/2019
#2
该行不会分配给新的 Map.Entry 对象,它只会强制转换为允许使用的对象以及与当前对象进行比较所需的方法Map.Entry<?,?> e = (Map.Entry<?,?>)o;
o
Entry
getKey()
getValue()
Entry
java.lang.Object
上唯一可用的方法详述o
评论
0赞
Amit Agrawal
1/25/2019
谢谢!那么,就地铸型会更加优化吗?
0赞
azro
1/25/2019
@AmitAgrawal 我不明白你的意思对不起
0赞
Amit Agrawal
1/25/2019
我的意思是“(Map.Entry<?,?>)o.getKey()”,但随后它会键入键而不是对象 o。 谢谢,@arzo。
0赞
azro
1/25/2019
@AmitAgrawal你可以做,但在这里,因为你也需要这个值,你必须做两次,一次是可以的,但是当更多时,强制转换并存储在一个变量中((Map.Entry<?,?>)o).getKey()
0赞
Amit Agrawal
1/28/2019
对,明白了。谢谢!
评论