欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

hash碰撞

程序员文章站 2022-10-03 19:02:35
这里写自定义目录标题JAVA HashMap 如何处理hash碰撞JAVA HashMap 如何处理hash碰撞jdk1.8 hashmap使用数组加链表让hashmap既能快速查找的同时也能快速插入删除。当插入的key的hashCode发生冲突时,会在Node[]数组冲突的位置挂上链表,当链表达到一定长度后,链表会转为红黑树,时间复杂度会从O(n)变成O(log n)。final V putVal(int hash, K key, V value, boolean onlyIf...

JAVA HashMap 如何处理hash碰撞

jdk1.8 hashmap使用数组加链表让hashmap既能快速查找的同时也能快速插入删除。当插入的key的hashCode发生冲突时,会在Node<K,V>[]数组冲突的位置挂上链表,当链表达到一定长度后,链表会转为红黑树,时间复杂度会从O(n)变成O(log n)。

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;//初始化hashmap的容量和阈值
        if ((p = tab[i = (n - 1) & hash]) == null)//(n - 1) & hash 等于 n % hash,根据key的hash值计算数组位置。n为2的幂次,这样可以降低hash碰撞的几率,在数组中分布更均匀。
            tab[i] = newNode(hash, key, value, null);//若没有hash冲突,新增Node。
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                //key已存在,直接替换Value
                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;
                    }
                    //在链表中找到输入的key,返回节点,替换Value
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    //指向下一个节点
                    p = e;
                }
            }
            //替换新value
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                //返回旧值
                return oldValue;
            }
        }
        ++modCount;
        //当容量超过阈值,resize进行扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

本文地址:https://blog.csdn.net/weixin_43074782/article/details/110822760