Hash冲突

Hash冲突,第1张

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中,有一个很重要的底层代码红黑树解决了这个问题

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

原文地址: http://outofmemory.cn/zaji/5597760.html

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

发表评论

登录后才能评论

评论列表(0条)

保存