美文网首页
hashcode返回0会出现什么问题

hashcode返回0会出现什么问题

作者: 0一缕星光0 | 来源:发表于2019-10-20 18:18 被阅读0次

重写hashcode的时候都是按照推荐方法,从来没有仔细考虑为什么不可以直接返回一个常数

结论

hashmap是通过hashcode来确定来确定槽位的,如果hashcode相同,则认为槽位冲突,需要使用链地址法解决冲突,降低了hashmap的效率。

源码

hashmapput源码

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

而其中hash(key)的源码

static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

如果keyhashCode返回0,则0>>>16依然为0,而0^0还是0,那么除第一个object外其他所有的object存入HashMap时都会冲突,HashMap的效率就降低为O(log(n))了。

相关文章

网友评论

      本文标题:hashcode返回0会出现什么问题

      本文链接:https://www.haomeiwen.com/subject/dbsamctx.html