<小时/>
我检查了源代码:
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()”方法被调用,所以如果我想在 map 中放置一个自定义对象,我只能重写“equal()”方法。所以我做了一个实验,结果是否定的...我必须重写“equals()”和“hashCode()”。所以我的问题是:
- 为什么必须重写这两个方法(equals()、hashCode())。
- “==”操作内部是否调用“hashCode()”方法?
最佳答案
这是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()
。
其他 map 类型可能确实不依赖于此方法被重写。
关于java - 在 Java 中调用 Map containsKey(E e) 时会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22112400/