我查了源代码:
public boolean containsKey(Object key) {
Iterator<Map.Entry<K,V>> i = entrySet().iterator();
if (key==null) {
while (i.hasNext()) {
Entry<K,V> e = i.next();
if (e.getKey()==null)
return true;
}
} else {
while (i.hasNext()) {
Entry<K,V> e = i.next();
if (key.equals(e.getKey()))
return true;
}
}
return false;
}
public boolean equals(Object obj) {
return (this == obj);
}
从源代码中,它只显示已经调用的“equal()”方法,所以如果我想在地图中放置一个自定义对象,我只能覆盖“equal()”方法。所以我做了一个实验,结果是否定的......我必须覆盖“equals()”和“hashCode()”。所以我的问题是:
答案 0 :(得分:3)
这是AbstractMap
的实施。覆盖它的HashMap
按如下方式实现:
public boolean containsKey(Object key) {
return getEntry(key) != null;
}
final Entry<K,V> getEntry(Object key) {
if (size == 0) {
return null;
}
int hash = (key == null) ? 0 : hash(key);
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;
}
final int hash(Object k) {
int h = hashSeed;
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
h ^= k.hashCode();
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
如您所见,这取决于hashCode()
。
其他地图类型可能确实不依赖于此方法被覆盖。
答案 1 :(得分:3)
来自Object.equals API:通常需要在重写此方法时覆盖hashCode方法,以便维护hashCode方法的常规协定,该方法声明相等对象必须具有相等的哈希码。您可以在“Effective Java”中找到更详细的说明。第9项:覆盖equals时始终覆盖hashCode。
不,它不是,它只是指针比较,就像比较两个整数