Java教程

Hash冲突

本文主要是介绍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<K,V> e = (Entry<K,V>) 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<K,V> entry = (Entry<K,V>)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<K,V> e = (Entry<K,V>) tab[index];
        tab[index] = new Entry<>(hash, key, value, e);

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

解决方法:

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

这篇关于Hash冲突的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!