zoukankan      html  css  js  c++  java
  • 2550--HashMap源码解析

    JDK版本 1.8

    结构:

    HashMap实现了Map Cloneable Serializable接口;

    基础了AbstractMap类,AbstractMap提供一些通用方法,如put remove等,但子类一般会重写put等方法;

    public class HashMap<K,V> extends AbstractMap<K,V>
        implements Map<K,V>, Cloneable, Serializable{
            
        }
    

    HashMap中定义了一些常量

    DEFAULT_INITIAL_CAPACITY  1 << 4 默认初始化容量值
    MAXIMUM_CAPACITY  1 << 30 最大容量值
    DEFAULT_LOAD_FACTOR 0.75f 默认负载因子
    TREEIFY_THRESHOLD 8 树化门槛值 
    UNTREEIFY_THRESHOLD 6 反树化门槛值 
    MIN_TREEIFY_CAPACITY 64 最小树化容量
    

    数据结构节点

    HashMap中定义了2个重要的数据结构,Node和TreeNode

    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;
        
        
        // hashCode值是key和value的hashcode取异或值
        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }
    }
    

    存储节点Node的容器

    // 实际上就是一个Node数组
     transient Node<K,V>[] table;
    

    hash方法
    相当于是HashMap自己的取Hash值的方法

        // 将key的hashcode值和hashcode值的低16值进行异或  记过就是在HashMap中的hash值
        static final int hash(Object key) {
            int h;
            return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
        }
    

    HashMap的put方法实现

    put函数大致的思路为:

    1. 对key的hashCode()做hash,然后再计算index;
    2. 如果没碰撞直接放到bucket里;(实际上是看index所在的位置是否有节点)
    3. 如果碰撞了,以链表的形式存在buckets后;
    4. 如果碰撞导致链表过长(大于等于TREEIFY_THRESHOLD),就把链表转换成红黑树;
    5. 如果节点已经存在就替换old value(保证key的唯一性)
    6. 如果bucket满了(超过load factor*current capacity),就要resize。

    put()方法是public的,会调用putVal()方法。

    计算index,通过i = (n - 1) & hash来确定桶的位置 再根据桶是否为空(以及桶元素的长度 延长链表或者变树)
    

    代码

    
    
        // 先对key进行hash计算  再调用putVal去存
        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; // table的临时引用
            Node<K,V> p; // p是桶位置上存放的节点
            int n, i; // n存放table数组的长度 i是元素数组下标 即桶位置
            // 判断table是否为null 或者容量为空 是则初始化tablesize
            if ((tab = table) == null || (n = tab.length) == 0)
                n = (tab = resize()).length;
                
            // 桶位置上的节点为null 则创建一个节点(使用本次存放的keyvalue)
            // ***计算位置索引 i = (n - 1) & hash
            if ((p = tab[i = (n - 1) & hash]) == null)
                tab[i] = newNode(hash, key, value, null);
            else {
                // 如果桶位置有节点 则验证是否是同一个hash值 是则替换value
                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)
                //  如果桶节点元素已经是树节点 则调用putTreeVal()放入树中
                    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的对应节点 则break
                        if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                            break;
                        p = e;
                    }
                }
                // 如果映射存在 则根据onlyIfAbsent进行存储
                if (e != null) { // existing mapping for key
                    V oldValue = e.value;
                    if (!onlyIfAbsent || oldValue == null)
                        e.value = value;
                    afterNodeAccess(e);
                    return oldValue;
                }
            }
            // 更新计数器+1
            ++modCount;
            // 如果size大于阈值 则扩容
            if (++size > threshold)
                resize();
            // LinkedHashMap的回调 对节点插入完成后的操作
            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)
                    // 将老容量值右移1位 即乘以2  并将阈值也翻倍
                    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);
            }
            
            // 如果新阈值为0 则按重新计算阈值
            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) {
                // 老table不为null 则遍历
                for (int j = 0; j < oldCap; ++j) {
                    Node<K,V> e;
                    if ((e = oldTab[j]) != null) {
                        oldTab[j] = null;
                        if (e.next == null)
                            // 通过 e.hash & (newCap - 1)来重新计算桶位置
                            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;
        }
    
  • 相关阅读:
    使用vue-lazyload 加载图片遇到的坑
    nvm 配置安装全局nodejs
    原生 ajax 请求
    angular5 引入第三方插件
    ionic3 组件引用报错问题
    有1到10w这个10w个数,去除2个并打乱次序,如何找出那两个数
    判断数据类型
    统计字符串有多少字节
    php
    数组 、 字符串 简单去重
  • 原文地址:https://www.cnblogs.com/starmoon1994/p/9966710.html
Copyright © 2011-2022 走看看