栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

假设您没有覆盖

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/464342.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号