我有一个关于 Java Hashmap
的小问题。如果我这样重写 hashCode
方法:
@Override
public int hashCode(){
return 9;
}
这将导致所有 HashMap
键具有相同的索引。它们将被放置在 map 中的链表结构中,还是 map 仅包含已替换所有其他键的最后一个键?
最佳答案
假设您没有覆盖 equals
方法以始终返回 true,它们将被放置在映射中的链表结构中。不同的key可能有相同的hashCode,但是如果所有的key有相同的hashCode,你的HashMap就会变成一个链表,这就违背了使用这个结构的初衷。
您可以在 HashMap
实现中亲眼看到它:
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key.hashCode()); // hash would always be the same if hashCode is constant
int i = indexFor(hash, table.length); // i would always be the same if hashCode is constant
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { // the key is searched using the
// equals method
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
关于java - 如果哈希码被重写以使其仅返回一个常数,Hashmap 键将如何表现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26674729/