java - 如果哈希码被重写以使其仅返回一个常数,Hashmap 键将如何表现?

标签 java hashmap hashcode

我有一个关于 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/

相关文章:

java - 即使ECS AWS上有许多可用内核,Runtime.getRuntime()。availableProcessors()仍返回1

java - 将数据插入具有大量列的表中

java - Struts 2 如何显示 map 复选框列表

java - 关于重写 java 中的 equals 方法

java - Effective Java教科书中的哈希码示例需要解释

java - 奇怪的 Java 哈希码(使用 Lombok)非确定性行为

java - 在 Java 中捕获标准输出的内容

java - 在Java中将余弦/正弦转换为角度

hashmap - 如何有效地从 HashMap 中查找和插入?

java - 如何使用java8中的流映射从类对象列表生成 HashMap 或哈希表?