栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Hash冲突

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

Hash冲突

什么是Hash冲突 先看一下源码:
private void addEntry(int hash, K key, V value, int index) {
        modCount++;

        Entry tab[] = table;
        if (count >= threshold) {
            // Rehash the table if the threshold is exceeded
            rehash();

            tab = table;
            hash = key.hashCode();
            index = (hash & 0x7FFFFFFF) % tab.length;
        }

        // Creates the new entry.
        @SuppressWarnings("unchecked")
        Entry e = (Entry) tab[index];
        tab[index] = new Entry<>(hash, key, value, e);
        count++;
    }
public synchronized V put(K key, V value) {
        // Make sure the value is not null
        if (value == null) {
            throw new NullPointerException();
        }

        // Makes sure the key is not already in the hashtable.
        Entry tab[] = table;
        int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;
        @SuppressWarnings("unchecked")
        Entry entry = (Entry)tab[index];
        for(; entry != null ; entry = entry.next) {
            if ((entry.hash == hash) && entry.key.equals(key)) {
                V old = entry.value;
                entry.value = value;
                return old;
            }
        }

        addEntry(hash, key, value, index);
        return null;
    }

这一段代码是来自hashTable里面的源码,这段代码是实现添加元素的一个最重要的操作。

其中有一个最重要的一段代码

就是下面这一段

 int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;
 Entry e = (Entry) tab[index];
        tab[index] = new Entry<>(hash, key, value, e);

这个里面有一个index,也就是所存进去的数的一个索引值。里面的有一个%,也就是取余运算符,使用这样一个取余运算符会导致一键事情发生,那就是有的时候会出现一个相同的值,这个时候前值会被后值所覆盖,这就是所谓的哈希冲突。

解决方法:

在jdk1.8中,有一个很重要的底层代码红黑树解决了这个问题

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

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

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