hashCode() 和 HashMap 中的 key hash
hashCode() and key hash in HashMap
假设 String A = "c"
, Character B = 'c'
.
我明白 A.hashCode() == B.hashCode()
但 A.equals(B) == false
.
但是,如果你把A
变成一个HashMap
作为key。然后调用 hashMap.contains(B)
returns false 尽管它们具有相同的 hashCode
。下面是 Java 如何实现 HashMap
.
中的一些功能
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
如您所见,HashMap
仅对键的 hashCode()
进行操作。那为什么contains()
可以returnfalse
?
why the contains could return false?
getNode
可能 return null
。这意味着找不到 key
的节点。哈希函数只是对 HashMap
.
中不可用的 key
进行哈希处理
第一个A.equals(B)
是假的而且String.equals(Object o)
有这个代码
if (anObject instanceof String) {
//comparing strings
}
return false;
同时 containsKey()
调用 getNode()
,它使用 equals
来区分相等的对象和具有相同 hashCode 的对象(哈希冲突)。
假设 String A = "c"
, Character B = 'c'
.
我明白 A.hashCode() == B.hashCode()
但 A.equals(B) == false
.
但是,如果你把A
变成一个HashMap
作为key。然后调用 hashMap.contains(B)
returns false 尽管它们具有相同的 hashCode
。下面是 Java 如何实现 HashMap
.
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
如您所见,HashMap
仅对键的 hashCode()
进行操作。那为什么contains()
可以returnfalse
?
why the contains could return false?
getNode
可能 return null
。这意味着找不到 key
的节点。哈希函数只是对 HashMap
.
key
进行哈希处理
第一个A.equals(B)
是假的而且String.equals(Object o)
有这个代码
if (anObject instanceof String) {
//comparing strings
}
return false;
同时 containsKey()
调用 getNode()
,它使用 equals
来区分相等的对象和具有相同 hashCode 的对象(哈希冲突)。