hash 冲突解决办法

2023-03-01 15:59:46 浏览数 (1)

hash 碰撞冲突

hashCode 方法是为了产生不同的 hash 值, 但是当两个对象的 hash 值一样时,会发生碰撞冲突

Hash 冲突的解决办法

  • 开放地址法;
  • 再hash的方法;
  • 拉链法;
  • 建立公共溢出区法;

开发地址法

基本思想:当发生地址冲突的时候,按照某种方法继续探测哈希表中的其他存储单元,直到找到空位置为止;

测试代码:

代码语言:javascript复制
public class Test1 {  
  
    //线性探测再散列  
    public static int[] m1(int[] arr){  
        if (arr==null || arr.length == 0){  
            return null;  
        }  
        int[] arr1 = new int[arr.length];  
        for (int i = 0;i<arr.length;i  ){  
            int p = arr[i]%(arr1.length);  
            if (arr1[p]==0){  
                arr1[p] = arr[i];  
            }else {  
                for (int j = 1 ; j<5;j  ){  
                    int p1 = (p j)%(arr1.length);  
                    if (arr1[p1]==0){  
                        arr1[p1] = arr[i];  
                    }  
                }  
            }  
        }  
        return arr1;  
    }  
  
    //二次探测再散列  
    public static int[] m2(int[] arr){  
        if (arr==null || arr.length == 0){  
            return null;  
        }  
  
        int[] arr1 = new int[arr.length];  
  
        for (int i = 0;i<arr.length;i  ){  
            int p = arr[i]%(arr1.length);  
            if (arr1[p]==0){  
                arr1[p] = arr[i];  
            }else {  
                for (int j = 1 ; j <= 5/2;j  ){  
                    int p1 = (p j*j)%(arr1.length);  
                    int p2 = (p-j*j)%(arr1.length);  
                    if (p1<=arr.length && arr1[p1]==0){  
                        arr1[p1] = arr[i];  
                    }  
                    if (p2>=0 && arr1[p2]==0){  
                        arr1[p2] = arr[i];  
                    }  
                }  
            }  
        }  
        return arr1;  
    }  
  
    //伪随机再散列  
    public static int[] m3(int[] arr){  
        if (arr==null || arr.length==0){  
            return null;  
        }  
        int[] arr1 = new int[arr.length];  
        for (int i = 0;i<arr.length;i  ){  
            int p = arr[i]%(arr1.length);  
            if (arr1[p]==0){  
                arr1[p] = arr[i];  
            }else {  
                while (true){  
                    int p1 = (int) ((p arr.length*Math.random())%(arr1.length));  
                    if (p1<=arr.length-1 && arr1[p1]==0){  
                        arr1[p1] = arr[i];  
                        break;  
                    }  
                }  
            }  
        }  
        return arr1;  
    }  
    //数组输出函数  
    public static void arrayPrint(int[] arr){  
        if (arr == null){  
            System.out.println("数组为null");  
        }else {  
            for (int k = 0 ;k<arr.length;k  ){  
                System.out.print(arr[k] " ");  
            }  
            System.out.println();  
        }  
    }  
  
    public static void main(String[] args){  
        int[] arr = {13,45,34,56,33};  
  
  
        int[] arr1 = m1(arr);  
        int[] arr2 = m2(arr);  
        int[] arr3 = m3(arr);  
        arrayPrint(arr2);  
        arrayPrint(arr1);  
        arrayPrint(arr3);  
    }  
}  

其实 ThreadLocalMap 中的就用的开放地址法,不断的进行线性探测, 通过nextIndex()不断获取table上得槽位,直到遇到第一个为null的地方,此处也将是存放具体entry的位置。

代码语言:javascript复制
private void set(ThreadLocal<?> key, Object value) {

            // We don't use a fast path as with get() because it is at
            // least as common to use set() to create new entries as
            // it is to replace existing ones, in which case, a fast
            // path would fail more often than not.

            Entry[] tab = table;
            int len = tab.length;
            int i = key.threadLocalHashCode & (len-1);

            for (Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(i, len)]) {
                ThreadLocal<?> k = e.get();

                if (k == key) {
                    e.value = value;
                    return;
                }

                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }

            tab[i] = new Entry(key, value);
            int sz =   size;
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
        }
公式

所用公式 H(key) = (H(key) di)mod m;其中i = 1、2、3.....k(k<m-1),H(key)为关键字key的直接hash地址;M为hash表的长度;

di为再次探测时的地址增量;根据di的不同取法,有不同的称呼;

  • 线性探测再散列:di = 1、2、3、4....k (k<m-1)
  • 二次探测再散列:di = 1^2,-1^2,2^2,-2^2.....k^2,-k^2 (k<=m/2)
  • 伪随机再散列:di = 伪随机数

再 hash 法

基本思想:有多个不同的Hash函数,当发生冲突时,使用第二个,第三个,…,等哈希函数计算地址,直到无冲突。虽然不易发生聚集,但是增加了计算时间

链地址法

基本思想:每个哈希表节点都有一个next指针,多个哈希表节点可以用next指针构成一个单向链表,被分配到同一个索引上的多个节点可以用这个单向链表连接起来 HashMap 中 hash 冲突的解决办法,就是链地址法, 如果当前桶上发生 hash 冲突,就,将当前值放到链表尾。

源码示例:

代码语言:javascript复制
 final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ;   binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
          modCount;
        if (  size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

建立公共溢出区

基本思想:将 hash 表为基本表和溢出表两部分,凡是和基本表冲突发生冲突的元素,一律填入溢出表。

参考资料
  • https://www.cnblogs.com/lyfstorm/p/11044468.html
  • https://www.iteye.com/blog/taoyongpan-2401102

0 人点赞