如果哈希代码被覆盖以致它只返回一个常数,哈希图键将如何表现? [英] How will Hashmap key behave if hash code is overridden such that it returns only a constant number?

查看:104
本文介绍了如果哈希代码被覆盖以致它只返回一个常数,哈希图键将如何表现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于Java Hashmap 的小问题。如果我重写 hashCode 这样的方法:

I have a small question about Java Hashmap. If I override the hashCode method such that:

@Override
public int hashCode(){
  return 9;
}

这将导致所有 HashMap 键具有相同的索引。他们会被放置在地图中的链表结构中,还是地图中只包含最后一个已替换所有其他键的键?

This will cause all the HashMap keys to have the same index. Will they be placed in a linked list structure in the map or will the map only contain the last key which has replaced all the other keys?

推荐答案

假设您没有重写 equals 方法以始终返回true,它们将被放置在映射中的链接列表结构中。不同的密钥可能具有相同的hashCode,但是如果所有密钥都具有相同的hashCode,那么您的HashMap将成为链表,这首先破坏了使用此结构的目的。

They will be placed in a linked list structure in the map, assuming you didn't override the equals method to always return true. Different keys may have the same hashCode, but if all the keys have the same hashCode, your HashMap would become a linked list, which defeats the purpose of using this structure in the first place.

你可以在 HashMap 实现中看到它自己:

You can see it for yourself in a HashMap implementation :

/**
 * 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;
}

这篇关于如果哈希代码被覆盖以致它只返回一个常数,哈希图键将如何表现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆