如果哈希码被覆盖(仅返回一个常数),哈希码键将如何工作?

如果哈希码被覆盖(仅返回一个常数),哈希码键将如何工作?,第1张

如果哈希码被覆盖(仅返回一个常数),哈希码键将如何工作?

假设您没有覆盖

equals
始终返回true
的方法,它们将放置在地图的链接列表结构中。不同的键可能具有相同的hashCode,但是如果所有键都具有相同的hashCode,则您的HashMap将成为链接列表,这首先使使用此结构的目的无效。

您可以在

HashMap
实现中亲自看到它:

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


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5439838.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-11
下一篇2022-12-11

发表评论

登录后才能评论

评论列表(0条)

    保存