美文网首页
HashMap源码分析详解

HashMap源码分析详解

作者: 一如既往wfqwfq | 来源:发表于2019-09-27 09:43 被阅读0次

1、简介

在jdk1.7中,HashMap采用数组+链表(拉链法)。因为数组是一组连续的内存空间,易查询,不易增删,而链表是不连续的内存空间,通过节点相互连接,易删除,不易查询。HashMap结合这两者的优秀之处来提高效率。

而在jdk1.8时,为了解决当hash碰撞过于频繁,而链表的查询效率(时间复杂度为O(n))过低时,当链表的长度达到一定值(默认是8)时,将链表转换成红黑树(时间复杂度为O(lg n)),极大的提高了查询效率。

2、成员变量

//默认初始化容量 16(数组大小或者说桶的个数)
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; 
//数组最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
//负载因子,超过数组长度的0.75就扩容
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//链表转红黑树的阀值,链表长度大于等于8时可尝试转为红黑树
static final int TREEIFY_THRESHOLD = 8;
//红黑树转链表的阀值
static final int UNTREEIFY_THRESHOLD = 6;
//链表转红黑树的另一个条件,数组容量需大于等于64
static final int MIN_TREEIFY_CAPACITY = 64;

3、put方法

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //判断哈希表是否为空,或者长度为0,是则进行扩容
        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);
                        //数组长度大于7时,链表转红黑树
                        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;
                }
            }
            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;
    }

put方法图解:

image.png

4、treeifyBin方法(链表转红黑树)

final void treeifyBin(Node<K,V>[] tab, int hash) {
       int n, index; Node<K,V> e;
       //如果哈希表长度小于64,则不转为红黑树,只做扩容
       if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
           resize();
        //哈希表长度大于等于64,链表长度大于8的转为红黑树
       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);
       }
   }

5、get方法

final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        //判断哈希表中是否存在这个key
        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;
}

6、resize()方法

相关文章

网友评论

      本文标题:HashMap源码分析详解

      本文链接:https://www.haomeiwen.com/subject/rheiuctx.html