zoukankan      html  css  js  c++  java
  • HashMap源码深入研究

    简介

    • HashMap是采用链表和位桶来来实现的,由于一个位桶存在元素太多会导致get效率低,因此在jdk1.8中采用的红黑树实现,当链表长度大于TREEIFY_THRESHOLD(值为8)时会转换为红黑树来提高查询效率。
    • HashMap是一种以键值对存储的框架,它是Map的实现类,提供了Map的基础操作,与HashTalbe不同的是HashMap不是线程安全的,key和value都是允许为null的;另外hashmap存储的内容顺序会变化的。
    • HashMap对与get和put操作提供了相对稳定的性能;如果注重Iteration迭代集合的性能,则不能设置初始化容量(capacity)太高或者负载因子(load factor)太低。影响HashMap性能的两个重要参数是初始化容量(initial capacity)和负载因子(load factor),初始化容量是至哈希表在创建时候的桶(bucket)的个数,负载因子是当哈希表放满的时候进行的增量系数,默认为0.75。
    • HashMap默认是线程不安全的 ,如果需要同步需要通过Cllections工具类进行包装:Map m = Collections.synchronizedMap(new HashMap(...));

    示意图

    纯手工画的,请容忍_! image

    关系图

    image

    使用示例

    HashMap<Object, Object> hashMap = new HashMap<>();
            //新增
            hashMap.put("name","张三");
            hashMap.put("age",18);
            //删除
            hashMap.remove("name");
            //修改
            hashMap.replace("age",16);
            //查询
            hashMap.get("age");
            //判断是否包含
            hashMap.containsKey("age");
            hashMap.containsValue(18);
    
            //循环1
            Set<Map.Entry<Object, Object>> entries = hashMap.entrySet();
            for (Map.Entry<Object, Object> entry:entries){
                System.out.println("key="+entry.getKey()+" value="+entry.getValue());
            }
            //循环2
            Set<Object> keys = hashMap.keySet();
            for(Object key:keys){
                System.out.println("key="+key+" value="+hashMap.get(key));
            }
            //清除
            hashMap.clear();

    原理分析

    HashMap的初始化

    初始化内容主要是容量大(initialCapacity)小和负载因子(loadFactor)的设定,table下次扩容的极限值(threshold),new的时候并没有真正的初始化容器。

    • 默认初始化-所有系数使用默认值,初始容量=16,负载因子=0.75
    //默认初始化容量
    static final int DEFAULT_INITIAL_CAPACITY = 16;
    //最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30;
    //链表对象数组
    transient Node<K,V>[] table;
    //加载因子
    final float loadFactor;
    //极限值,当键值对数量大于等于threshold,则触发扩容方法resize()
    //第一次初始化时候:threshold=(int)(loadFactor*initialCapacity),只有手动设置initialCapacity时候才需要第一次初始化
    //第二次初始化的时候:threshold=(threshold*loadFactor)
    //初始化后的扩容:newThr=threshold<<1,相当于threshold*2
    int threshold;
    
    public HashMap() {
            this.loadFactor = DEFAULT_LOAD_FACTOR; 
        }
    • 自定义初始化容量,其他参数使用默认值
    public HashMap(int initialCapacity) {
            this(initialCapacity, DEFAULT_LOAD_FACTOR);
        }
    • 定义初始化容量和负载因子
    public HashMap(int initialCapacity, float loadFactor) {
            if (initialCapacity < 0)
                throw new IllegalArgumentException("Illegal initial capacity: " +
                                                   initialCapacity);
            if (initialCapacity > MAXIMUM_CAPACITY)
                initialCapacity = MAXIMUM_CAPACITY;
            if (loadFactor <= 0 || Float.isNaN(loadFactor))
                throw new IllegalArgumentException("Illegal load factor: " +
                                                   loadFactor);
            this.loadFactor = loadFactor;
            //将初始化容量转换为2的n次幂
            this.threshold = tableSizeFor(initialCapacity);
        }
    //将cap向上转化为2的n次幂,如cap=17转化后为32    
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

    HashMap.put(key,value)分析

    put操作

    1、第一次新增键值对时候,首先进行内部Node<K,V>[] table初始化
    2、新增一个键值对,如果key已经存在则进行替换原来value,如果不存在则进行新增。

    public V put(K key, V value) {
            //放入键值对
            //最后两个参数为 false表名修改已存在的值,否则不进行修改,最后一个true在LinkedHashMap使用
            return putVal(hash(key), key, value, false, true);
        }
        
    //对key进行hash计算,获取hash值
    static final int hash(Object key) {
            int h;
            return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
        }
    //存放键值对
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    //如果table为空或者长度为0,则进行初始化,初始化在下面进行分析
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    //计算key的下标(n-1)&hash,判断当前下标中是否已经有元素,没有则进行直接新增
    //key的下标算法(n-1)是table的最大下标,然后与hash进行与计算则获取最终下标,
    //这种下标计算不仅保证了下标在0-15之间的某个值,而且也保证了下标的均匀分布和计算效率
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    //如果当前下标已经存在元素则进行下列计算
    else {
        Node<K,V> e; K k;
        //如果已经存在相同的key,则将原来的元素赋值为e
        if (p.hash == hash &&((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        //如果原来的元素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);
                    //如果链表的长度大于等于7的时候将链表转化为红黑树(jdk1.8新增的)
                    //因为如果存在大量数据的hash值相等,怎会产生很大的链表,
                    //而链表的查询效率较低,所以在1.8版本后新增了红黑树结构。
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        //将链表转换为红黑树
                        treeifyBin(tab, hash);
                    break;
                }
                //如果在链表的某个环节碰到相同的key则停止循环
                if (e.hash == hash &&((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        //已经存在相同的key,只需将新的value赋值给老的value即可
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            //onlyIfabsent是用来决定是否覆盖已有的key的value,在hashmap中默认false
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    //最终判断容器table的大小+1是否超过table的极限值threshold,如果超过则进行扩容
    //扩容的方式是newThr=threshold<<1,相当于threshold*2
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
    }

    resize分析

    初始化table或者扩容的时候需要执行resize。

    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) {
                //如果原来的容量大于MAXIMUM_CAPACITY=1073741824则将threshold设为
                //Integer.MAX_VALUE=2147483647 接近MAXIMUM_CAPACITY的两倍
                if (oldCap >= MAXIMUM_CAPACITY) {
                    threshold = Integer.MAX_VALUE;
                    return oldTab;
                }
                //否则设为newThr为原来的两倍
                else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                         oldCap >= DEFAULT_INITIAL_CAPACITY)
                    newThr = oldThr << 1; // double threshold
            }
            //如果原来的thredshold大于0则将容量设为原来的thredshold
            //在第一次带参数初始化时候会有这种情况
            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;
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
            table = newTab;
            如果原来的table有数据,则将数据复制到新的table中
            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;
        }

    treeifyBin将某个链表转为红黑树

    hash是需要转化为红黑树的链表哈希

    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            TreeNode<K,V> hd = null, tl = null;
            do {
                TreeNode<K,V> p = replacementTreeNode(e, null);
                if (tl == null)
                    hd = p;
                else {
                    p.prev = tl;
                    tl.next = p;
                }
                tl = p;
            } while ((e = e.next) != null);
            if ((tab[index] = hd) != null)
                hd.treeify(tab);
        }
    }

    putTreeVal红黑树新增

    final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
                                           int h, K k, V v) {
                Class<?> kc = null;
                boolean searched = false;
                //获取树根
                TreeNode<K,V> root = (parent != null) ? root() : this;
                for (TreeNode<K,V> p = root;;) {
                    int dir, ph; K pk;
                     // hashMap元素的hash值用来表示红黑树中节点数值大小
                     // 当前节点值小于根节点,dir = -1
                     // 当前节点值大于根节点, dir = 1
                    if ((ph = p.hash) > h)
                        dir = -1;
                    else if (ph < h)
                        dir = 1;
                    else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                        return p;
                    // 当前节点的值等于根节点值
                    //如果当前节点实现Comparable接口,调用compareTo比较大小并赋值dir
                    //如果当前节点没有实现Comparable接口,compareTo结果等于0,则调用tieBreakOrder继续比较大小
                    // tieBreakOrder本质是通过比较k与pk的hashcode
                    else if ((kc == null &&
                              (kc = comparableClassFor(k)) == null) ||
                             (dir = compareComparables(kc, k, pk)) == 0) {
                        if (!searched) {
                            TreeNode<K,V> q, ch;
                            searched = true;
                            if (((ch = p.left) != null &&
                                 (q = ch.find(h, k, kc)) != null) ||
                                ((ch = p.right) != null &&
                                 (q = ch.find(h, k, kc)) != null))
                                return q;
                        }
                        dir = tieBreakOrder(k, pk);
                    }
    
                    TreeNode<K,V> xp = p;
                    if ((p = (dir <= 0) ? p.left : p.right) == null) {
                        Node<K,V> xpn = xp.next;
                        TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
                        // 如果当前节点小于根节点且左子节点为空 
                        //或者当前节点大于根节点且右子节点为空,直接添加子节点
                        if (dir <= 0)
                            xp.left = x;
                        else
                            xp.right = x;
                        xp.next = x;
                        x.parent = x.prev = xp;
                        if (xpn != null)
                            ((TreeNode<K,V>)xpn).prev = x;
                        //确保红黑树根节点是数组中该index的第一个节点
                        //平衡红黑树
                        moveRootToFront(tab, balanceInsertion(root, x));
                        return null;
                    }
                }
            }

    HashMap.get(key)分析

    get操作

    //根据key获取node,然后获取value
    public V get(Object key) {
            Node<K,V> e;
            return (e = getNode(hash(key), key)) == null ? null : e.value;
        }

    getNode链表查询

    //根据key的hash和key获取node
    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) {
                //判断链表的第一个node是否是想要的
                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;
        }

    getTreeNode树查询

    final TreeNode<K,V> getTreeNode(int h, Object k) {
                //判断当前树是否是parent(树根),如果不是则找到树根,然后从树根往下找
                return ((parent != null) ? root() : this).find(h, k, null);
            }
            
    final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
                TreeNode<K,V> p = this;
                //从树根循环往下找
                do {
                    int ph, dir; K pk;
                    TreeNode<K,V> pl = p.left, pr = p.right, q;
                    //根据hash大小来判断为左边分支还是右边分支
                    if ((ph = p.hash) > h)
                        p = pl;
                    else if (ph < h)
                        p = pr;
                    //如果hash相等并且key相等则返回treeNode(找到了!)
                    else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                        return p;
                    //如果左边为空则向右边找
                    else if (pl == null)
                        p = pr;
                    //如果右边为空则向左边找
                    else if (pr == null)
                        p = pl;
                    //如果不按哈希值排序,而是按照比较器排序,
                    //则通过比较器返回值决定进入左右结点
                    else if ((kc != null ||
                              (kc = comparableClassFor(k)) != null) &&
                             (dir = compareComparables(kc, k, pk)) != 0)
                        p = (dir < 0) ? pl : pr;
                    //找到直接返回treeNode,否则继续查找
                    else if ((q = pr.find(h, k, kc)) != null)
                        return q;
                    else
                        p = pl;
                //找到没有节点为止
                } while (p != null);
                return null;
            }

    HashMap.remove(key)分析

    根据key删除映射,并返回value,如果不存在key则返回null

    移除操作

    首先进行key的hash计算,然后根据hash(key)算出下标,找出对应Node,将Node赋值为null,返回value

    public V remove(Object key) {
            Node<K,V> e;
            return (e = removeNode(hash(key), key, null, false, true)) == null ?
                null : e.value;
        }

    removeNode移除节点

    final Node<K,V> removeNode(int hash, Object key, Object value,
                                   boolean matchValue, boolean movable) {
            Node<K,V>[] tab; Node<K,V> p; int n, index;
            //判断table是否为空,是否存在下标为index = (n - 1) & hash的节点
            //如果不存在则直接返回null
            if ((tab = table) != null && (n = tab.length) > 0 &&
                (p = tab[index = (n - 1) & hash]) != null) {
                Node<K,V> node = null, e; K k; V v;
                //判断链表/红黑树的第一个节点的key是否相等
                //相等则将p赋值为node
                if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                    node = p;
                //否则进行循环列表逐个判断
                else if ((e = p.next) != null) {
                    //判断是红黑树则通过红黑树方法查找
                    if (p instanceof TreeNode)
                        node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                    //否则直接进行循环列表逐个判断
                    else {
                        do {
                            if (e.hash == hash &&
                                ((k = e.key) == key ||
                                 (key != null && key.equals(k)))) {
                                node = e;
                                break;
                            }
                            p = e;
                        } while ((e = e.next) != null);
                    }
                }
                //判断通过以上操作获取node
                if (node != null && (!matchValue || (v = node.value) == value ||
                                     (value != null && value.equals(v)))) {
                    //如果node为树则进行树的移除操作
                    if (node instanceof TreeNode)
                        ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                    //如果是链表的第一个节点,将节点向后指向一位
                    else if (node == p)
                        tab[index] = node.next;
                    //否则是链表的某个非第一个节点
                    else
                        p.next = node.next;
                    ++modCount;
                    --size;
                    afterNodeRemoval(node);
                    return node;
                }
            }
            return null;
        }

    HashMap.clear()清除操作

    清除操作先将table的size赋值为0,然后进行循环table将Node赋值为null,清除所有数据HashMap的效率相对比较高

    public void clear() {
            Node<K,V>[] tab;
            modCount++;
            if ((tab = table) != null && size > 0) {
                size = 0;
                for (int i = 0; i < tab.length; ++i)
                    tab[i] = null;
            }
        }

    总结

    以上内容根据HashMap的创建,put,get,remove,clear方法进行了源码分析,通过源码分析我们了跟清楚的认识到HashMap的数据存放结构,存储、查询、移除、清除操作过程和HashMap的扩容方式,以及jdk1.8中链表转化为红黑树和红黑树的基本操作,如果发现又哪里不对或者你有更深的认识和补充请直接在下面留言或者通过关注微信告诉给我,然后分享给大家!

    参考资料

    想了解更多内容请关注微信哦,我在这里船上等你......

  • 相关阅读:
    LInux 安装 MySQL
    JS BUG 传递数字过大,数据值会变化
    tabs 标签样式
    【异常】IOException parsing XML document from class path resource [xxx.xml]
    云服务器启动tomcat巨慢,很慢
    Linux修改/etc/profile配置错误command is not found自救方法
    linux 安装 vsftpd服务
    为什么说 Vue 的响应式更新比 React 快
    在idea中使用git拉去最新代码并merge到本地代码中
    解决重新打开一个项目,idea需要重新配置maven的问题
  • 原文地址:https://www.cnblogs.com/mvilplss/p/7144146.html
Copyright © 2011-2022 走看看