hashmap 实现原理总结

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sessionsong/article/details/79594389

HashMap 实现原理

  1. 数据结构是基于哈希表实现的 (数据+链表+二叉树 (红黑树))
  2. 默认的加载因子是0.75 默认大小是 16
  3. 存储元素 put(key,value)
    a. 计算key 的hash 值, hash
    b. 根据上面得到的hash 值和数据的长度进行 取余操作,计算出 该元素在数据组的位置 i
    c. 如果位置i 没有元素 直接存储,
    如果有元素 那么也就是有多个元素会hash 到这个位置,需要用链表来存储, 如果链表的长度大于8了
    将会使用二叉树来存储
    这么做的目的: 取值快,存储的数据越大,越能体现出性能的差异
  4. HashMap 扩充原理
    当数据的容量超过 75%,会将数字的大小扩充一倍 (<<1) 并把所有的元素重新hash 到新数组当中去。
    所以这个地方需要注意: 尽量减少对数组的扩充,最好是在申明的时候设置数组长度,以减少因数组扩充,元素重新散列 hash,复制到新数组里面带来的性能问题。
    // HashMap  put 方法源码
    public V put(K key, V value) {
        // 给 putval 方法传递 key 的hash 值 用于计算该元素的数组小标
        return putVal(hash(key), key, value, false, true);
    }
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        // 判断tab 是否为空,如果为空  
        if ((tab = table) == null || (n = tab.length) == 0)
        // tab  为空 重新new tables  在 resize()方法中可以看到
            n = (tab = resize()).length;
            // 通过 (n-1)&hash 计算hash 后的 数组小标 i 并判断 tab[i] 是否已经存储了元素
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {  // 已经有数据了
            Node<K,V> e; K k;
            // hash 和key 都一样 表面是同一个元素 重复插入 更新values
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
                // 如果hash到同一个位置的元素超过了8个 那么就是 二叉树了 
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else { // 没到 8 个  用链表存储
                // 循环 找到链表中的最后一个元素 p 
                for (int binCount = 0; ; ++binCount) {
                    // p是当前链表的最后一个元素  新建一个 元素e 并连接到p.next
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        // 超过了 链表的默认最大大小(8) 把链表转为二叉树
                            treeifyBin(tab, hash);
                        break;
                    }
                    // 判断当前元素的key 和目标元素的key 是否一致,如果一致 表面是更新操作 更新p
                    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;
        //  如果 当前元素数+1 大于 当前 map 可以存放的最大数 (capacity * load factor) 对map 进行扩展  这个地方 也是最容易出现性能问题的地方,所以需要谨慎
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
  1. 获取元素 get(key)
    a. 计算key 的hash 值, hash
    b. 根据上面得到的hash 值和数据的长度进行 取余操作,计算出 该元素在数据组的位置 ,并取出该元素
    c. 通过key 判断该元素是不是目标元素 如果是 直接返回
    如果不是: 那就便利链表 找到 目标元素 并返回
 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) {
            // 如果map 中的第一个元素就满足  返回
            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;
    }

猜你喜欢

转载自blog.csdn.net/sessionsong/article/details/79594389