HashMap原理

Posted BarrysPN

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HashMap原理相关的知识,希望对你有一定的参考价值。

            HashMap是给予哈希表的Map接口实现。Map就是一组键(key)-值(value)的映射。Map的实现在java有:HashMap HashTable、TreeMap.    HashMap和HashTable区别:1️⃣ HashMap是key和value都可以为空,HasHTable不不能。 2️⃣ HashTable的方法是同步的 HashMap不是,类似vector和ArrayList。3️⃣ 默认大小HashMap 16 ,HashTable默认11。HashMap是我们日常开发中使用最多一种。

        

一、注释及基础变量

     

     jdk源码中注释都非常详细,通过注释就能简单了解用途、使用方式、实现原理、特点。来看下HashMap的几个注释:

这个注释描述HashMap的实现方式,特点(key,value都可以为空),非同步,并且是无序的。

来再看下变量:

/**

* The default initial capacity - MUST be a power of two.

*/

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 

map的默认大小 16

/**

* The maximum capacity, used if a higher value is implicitly specified

* by either of the constructors with arguments.

* MUST be a power of two <= 1<<30.

*/

static final int MAXIMUM_CAPACITY = 1 << 30;

map的最大容量

/**

* The load factor used when none specified in constructor.

*/

static final float DEFAULT_LOAD_FACTOR = 0.75f;

默认加载因子,用于map自动扩容。

/**

* The bin count threshold for using a tree rather than list for a

* bin.  Bins are converted to trees when adding an element to a

* bin with at least this many nodes. The value must be greater

* than 2 and should be at least 8 to mesh with assumptions in

* tree removal about conversion back to plain bins upon

* shrinkage.

*/

static final int TREEIFY_THRESHOLD = 8;

这个是map数据桶,使用链表还是树的一阀值,

/**

* The bin count threshold for untreeifying a (split) bin during a

* resize operation. Should be less than TREEIFY_THRESHOLD, and at

* most 6 to mesh with shrinkage detection under removal.

*/

static final int UNTREEIFY_THRESHOLD = 6;

当扩容时,桶中元素个数小于这个值

就会把树形的桶元素 还原(切分)为链表结构

/**

* The smallest table capacity for which bins may be treeified.

* (Otherwise the table is resized if too many nodes in a bin.)

* Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts

* between resizing and treeification thresholds.

*/

static final int MIN_TREEIFY_CAPACITY = 64;

树化中通道的阀值。

二、HashMap数据机构


 HashMap内部数据接口是链表散列,1.8版本做了优化提升它性能。

它的内部数据结构,就是一个数组,数组存放的是链表。数组在的每个位置,它注释中称为桶(bin),如果HashMap就是一这个结构保存数据,它的时间复杂度就是O(N),因为散列算法N(1)链表的话就O(N),jdk1.8优化对HashMap达到一定容量后进行树化,使用了红黑树,那么时间复杂度就是O(log(N))



三、重要源码

1、putVal()方法


   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;

        //数据通道内没有数据,直接创建一个Node,放入数据桶

        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 {

                //遍历树节点,把节点方入链表尾部,显然时间复杂度就O(n),binCount通道内列表长度大于8时进行树化,反之把数据插入到列表尾部。

                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;

    }

put方法实际内部直接调用这方法。

1️⃣ 首次添加数据数组的为空,首先调用resize(),扩容创建一个默认长度为16的数组。如果已有数据是resize()会,以2的n次方进行 扩容数组,然后在重新把链表插入进去。在这个过程如果出现多线程操作容易形成环造成死循环。

  //创建新的table,然后把原有的列表到添加到桶中,注意这个地方容易造成闭环,死循环

            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;

                        }

                    }

                }

            }

        }


2️⃣  继续往下如果数组长度满足,如果原来数据桶中有数据并且链表长度小于8则继续添加否则进行树化,如果桶的数组长度大于64并且桶内链表长度大于8,则进行进行树化(链表转换成为红黑二叉树)。


网上找的一个流程图觉得还不错:

四、总结

     通过对HashMap实现的学习总结,能让我们在选择使用更加得心应手避免不必要的bug,也可以学习下大神的学习思路。了解自己的短处例如java基础的位运算,好多人工作几年了都不知道怎么用。为什么源码中大量使用这个,找到问题就知道我们短板。



参考:http://www.importnew.com/20386.html

以上是关于HashMap原理的主要内容,如果未能解决你的问题,请参考以下文章

hashmap底层实现原理是啥?

HashMap原理 扩容机制及存取原理

HashMap源码分析及原理分析

HashMap----工作原理

HashMap----工作原理

HashMap底层实现原理/HashMap与HashTable区别/HashMap与HashSet区别