哈希表|避免+解决冲突的方法、如何实现一个HashMap、源码

哈希表

概念

不经过任何比较,一次性从表中得到要搜索的元素
数组,通过哈希函数使得元素的存储位置与关键码建立一一映射关系
  • put:插入元素

    • 根据key计算出存储位置存放value
  • get:搜索元素

    • 根据key得到存储位置取出value

冲突:不同的关键字通过相同哈希函数得到相同哈希地址

避免冲突的方法

哈希函数设计
  • 原则

    • 定义域包括需要存储的全部关键码
    • 地址能均匀分布在整个空间中
    • 简单
  • 常见函数

    • 直接定址法
    • 除留余数法
    • 平方取中法
负载因子的调节
  • 公式

    • 负载因子α=表中的元素个数/散列表的长度
  • 作用

    • 表示散列表的装满程度,α越大,说明表中元素很多,产生冲突的概率较大
  • 解决

    • 当α过大时,就调节哈希表中的数组大小(即扩容),降低冲突率

解决冲突的方法

闭散列
  • 线性探测
  • 二次探测
开散列/哈希桶
  • 具有相同地址的关键码归于同一子集合(桶),桶中的元素用链表连接,各链表的头节点保存在哈希表中

自主实现一个HashMap

get
  1. 根据key得到下标index
  • 求出key的hashCode()

    • 若key的K类型是自定义的,必须要覆写hashCode(),否则无法根据相同的key找到唯一的下标
    • 让hash中的每一位都参与到找下标的过程,使得找到的下标尽可能均匀
  • 利用hash得到合法的下标,前提是table.length必须是2的幂次方

  1. 使用下标找到链表的头节点的引用
  2. 在链表中,找到等于key的结点,返回该节点的value
  • 若key的K类型是自定义的,必须要覆写类的equals方法,保证能判断相等
    @Override
    public V get(K key) {
        //1.根据key得到下标
        //1.1求出key的hashCode();
        //若HashMap的K类型是自定义的类,必须要覆写hashCode(),否则无法根据相同的key找到唯一的下标
        int hash = key.hashCode();
        //让hash中的每一位都参与到找下标的过程,使得找到的下标,尽可能均匀
        hash = (hash >>> 16) ^ hash;
        //1.2利用hash得到合法的下标,前提是table.length 必须是 2 的幂次方
        int index = hash & (table.length - 1);

        //2.使用下标,找到链表的头节点的引用
        MyEntry<K, V> head = table[index];

        //3.在链表中,找到包含key的结点,返回该节点的value
        MyEntry<K, V> node = head;
        while (node != null) {
            //使用了key的equals方法。
            //如果使用自定义类作为HashMap的K,必须覆写类的equals方法,保证能判断是否相等
            if (key.equals(node.key)) {
                return node.value;
            }
            node = node.next;
        }
        return null;
    }
put
  1. 根据key得到下标index

  2. 使用下标找到链表的头节点的引用

  3. 在链表中,找到等于key的结点,返回该节点的value

  4. 若链表遍历结束,未找到

    • 新建结点,将结点尾插到链表中
    • 表中的元素个数增加
  5. 计算负载因子是否超过阈值,超过则扩容

    • 创建长度扩大的新数组,保证新数组的长度仍为2的幂次方

    • 遍历表中的链表中的每一个元素

      • 根据每个元素的key找到新下标
      • 插入到链表中
    • 替换掉旧的table

    @Override
    public V put(K key, V value) {
        int hash = key.hashCode();
        hash = (hash >>> 16) ^ hash;
        int index = hash & (table.length - 1);
        MyEntry<K, V> head = table[index];
        MyEntry<K, V> node = head;
        while (node != null) {
            if (key.equals(node.key)) {
                //修改旧值,返回旧值
                V oldValue = node.value;
                node.value = value;
                return oldValue;
            }
            node = node.next;
        }

        //链表遍历结束,没有找到
        //新建结点,并且把结点插入到链表中
        MyEntry<K, V> entry = new MyEntry<>(key, value);

        //考虑多线程的情况,使用尾插
        if (head == null) {
            table[index] = entry;
        } else {
            MyEntry<K, V> last = head;
            while (last != null) {
                last = last.next;
            }
            last.next = entry;
        }

        size++;

        // 为了减少冲突率,所以需要考虑降低 size / table.length 的值
        // 设定一个阈值,当 size / table.length 高于某个值时,进行扩容
        // 所谓的扩容,就是保证 size 不变,让 table.length 变大
        // 进而,使得 size / table.length 降低,进而减少冲突率
        if (size * 1.0/table.length > LOADER_FACTOR_THRESHOLD) {
            resize();
        }

        return null;
    }

    //扩容,需要
    //1. 保证 table.length 仍然是 2 的幂次方
    //2. 因为 table.length 变化了,所以 key 对象的下标一定会变化
    //所以,需要把所有的 key,重新计算下标,重新插入
    private void resize() {
        //数组扩容
        MyEntry<K, V>[] newTable = new MyEntry[table.length * 2];

        for (int i = 0; i < table.length; i++) {
            MyEntry<K, V> head = table[i];
            MyEntry<K, V> node = head;
            while (node != null) {
                K key = node.key;
                V value = node.value;

                //利用key,找新的下标
                int hash = key.hashCode();
                hash = (hash >>> 16) ^ hash;
                int index = hash & (newTable.length - 1);

                //头插
                MyEntry<K, V> entry = new MyEntry<>(key, value);
                entry.next = newTable[index];
                newTable[index] = entry;

                node = node.next;
            }

        }

        //替换掉旧的table
        table = newTable;

    }

源码

get
    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    /**
     * Implements Map.get and related methods.
     *
     * @param hash hash for key
     * @param key the key
     * @return the node, or null if none
     */
    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }
put
    /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with {@code key}, or
     *         {@code null} if there was no mapping for {@code key}.
     *         (A {@code null} return can also indicate that the map
     *         previously associated {@code null} with {@code key}.)
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    /**
     * Implements Map.put and related methods.
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    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;
    }

    /**
     * Initializes or doubles table size.  If null, allocates in
     * accord with initial capacity target held in field threshold.
     * Otherwise, because we are using power-of-two expansion, the
     * elements from each bin must either stay at same index, or move
     * with a power of two offset in the new table.
     *
     * @return the table
     */
    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值