暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

HashMap原理及源码分析

生活不止眼前的代码 2018-10-02
196

1. HashMap原理
2. HashMap源码分析
3. HashMap在java8中的改变

hashmap原理

HashMap简单来说就是一个散列表,存储着key-value键值对

HashMap的存储结构是一个数组加链表的结构,在java8之后链表在长度超过TREEIFYTHRESHOLD树化阈值且map中的元素数量超过了MINTREEIFY_CAPACITY最小树化容量,则会转化成红黑树的结构

HashMap通过hash算法使在不考虑hash冲突的情况下查找方法的时间复杂度为O(1)



hashmap源码分析

  1. hashmap的初始化
    hashmap的初始默认容量是16,如果超过阈值则会扩容,在扩容的时候要重新计算hash值将其放入新的hashmap中,因此扩容操作是一个相当耗时的操作,我们在使用的时候应该根据实际需要指定初始容量,尽可能避免扩容

..

  1. /**

  2. * 指定初始容量的构造函数

  3. */

  4. public HashMap(int initialCapacity) {

  5.    this(initialCapacity, DEFAULT_LOAD_FACTOR);

  6. }


  7. /**

  8. * 无参构造函数的初始负载因子是0.75,默认容量是16

  9. */

  10. public HashMap() {

  11.    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted

  12. }

  1. put方法

hashmap在初始化的时候并不会去初始化数组,只有在put第一个元素的时候才会去初始化数组

put的流

put源码解析

  1. public V put(K key, V value) {

  2.    return putVal(hash(key), key, value, false, true);

  3. }


  4. final V putVal(int hash, K key, V value, boolean onlyIfAbsent,

  5.               boolean evict) {

  6.    Node<K,V>[] tab; Node<K,V> p; int n, i;

  7.    //判断table是否为空,table为空则进行初始化

  8.    if ((tab = table) == null || (n = tab.length) == 0)

  9.        n = (tab = resize()).length;

  10.    //判断索引位置有无元素,如果没有则创建node对象,存入该元素

  11.    if ((p = tab[i = (n - 1) & hash]) == null)

  12.        tab[i] = newNode(hash, key, value, null);

  13.    else {

  14.        Node<K,V> e; K k;

  15.        //如果该位置存在元素,且key值相同,则替换值

  16.        if (p.hash == hash &&

  17.                ((k = p.key) == key || (key != null && key.equals(k))))

  18.            e = p;

  19.        else if (p instanceof TreeNode)//hash值一样,但是key不同,且链表为红黑树结构,则往树中加入该元素

  20.            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);

  21.        else {

  22.            for (int binCount = 0; ; ++binCount) {

  23.                if ((e = p.next) == null) {

  24.                    //链表最后都没有key相同的元素,则在链表的最后加入该元素

  25.                    p.next = newNode(hash, key, value, null);

  26.                    //如果超过树化阈值,则将链表树化

  27.                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st

  28.                        treeifyBin(tab, hash);

  29.                    break;

  30.                }


  31.                //如果链表中有key相同的元素,则退出循环

  32.                if (e.hash == hash &&

  33.                        ((k = e.key) == key || (key != null && key.equals(k))))

  34.                    break;

  35.                p = e;

  36.            }

  37.        }

  38.        //e不为空则个e赋值

  39.        if (e != null) { // existing mapping for key

  40.            V oldValue = e.value;

  41.            if (!onlyIfAbsent || oldValue == null)

  42.                e.value = value;

  43.            afterNodeAccess(e);

  44.            return oldValue;

  45.        }

  46.    }

  47.    ++modCount;

  48.    //如果元素个数大于阈值,则扩容

  49.    if (++size > threshold)

  50.        resize();

  51.    afterNodeInsertion(evict);

  52.    return null;

  53. }

  1. get方法

get流程图

get源码解析

  1. public V get(Object key) {

  2.    Node<K,V> e;

  3.    return (e = getNode(hash(key), key)) == null ? null : e.value;

  4. }


  5. final Node<K,V> getNode(int hash, Object key) {

  6.    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;

  7.    // 判断table是否为空,table在该节点位置是否为空

  8.    if ((tab = table) != null && (n = tab.length) > 0 &&

  9.            (first = tab[(n - 1) & hash]) != null) {

  10.        // 判断该位置的第一个元素的key值是否和get的key值相等

  11.        if (first.hash == hash && // always check first node

  12.                ((k = first.key) == key || (key != null && key.equals(k))))

  13.            return first;

  14.        // 判断是否有下一个节点

  15.        if ((e = first.next) != null) {

  16.            // 如果是树结构就在树种查找该节点

  17.            if (first instanceof TreeNode)

  18.                return ((TreeNode<K,V>)first).getTreeNode(hash, key);

  19.            // 在链表中查找该节点

  20.            do {

  21.                if (e.hash == hash &&

  22.                        ((k = e.key) == key || (key != null && key.equals(k))))

  23.                    return e;

  24.            } while ((e = e.next) != null);

  25.        }

  26.    }

  27.    return null;

  28. }

  1. resize

  1. final Node<K,V>[] resize() {

  2.    Node<K,V>[] oldTab = table;

  3.    int oldCap = (oldTab == null) ? 0 : oldTab.length;

  4.    int oldThr = threshold;

  5.    int newCap, newThr = 0;

  6.    if (oldCap > 0) { //数组不为空

  7.        if (oldCap >= MAXIMUM_CAPACITY) {//超过了最大容量

  8.            threshold = Integer.MAX_VALUE;

  9.            return oldTab;

  10.        }

  11.        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&

  12.                oldCap >= DEFAULT_INITIAL_CAPACITY)

  13.            newThr = oldThr << 1; // 容量扩大两倍

  14.    }

  15.    else if (oldThr > 0) // 如果数组为空,指定了新增阈值-->带参初始化

  16.        newCap = oldThr;

  17.    else {               // 数组为空,没有指定新的阈值,采用默认初始值-->无参初始化

  18.        newCap = DEFAULT_INITIAL_CAPACITY;

  19.        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);

  20.    }

  21.    if (newThr == 0) { //按照给定的初始容量计算扩容后的新增阈值-->容量扩大两倍超出了最大值

  22.        float ft = (float)newCap * loadFactor;

  23.        newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?

  24.                (int)ft : Integer.MAX_VALUE);

  25.    }

  26.    threshold = newThr;

  27.    @SuppressWarnings({"rawtypes","unchecked"})

  28.    Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];

  29.    table = newTab;

  30.    if (oldTab != null) { //将原数组的元素放入扩容后的数组

  31.        for (int j = 0; j < oldCap; ++j) {

  32.            Node<K,V> e;

  33.            if ((e = oldTab[j]) != null) {

  34.                oldTab[j] = null;

  35.                if (e.next == null) //无后继几点,直接计算在新数组的位置,放入即可

  36.                    newTab[e.hash & (newCap - 1)] = e;

  37.                else if (e instanceof TreeNode) //为树节点的要拆分

  38.                    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);

  39.                else { // 单链表节点,将原数组中的链表元素拆分,一部分在原索引位置,一部分在原索引加原数组长度

  40.                    Node<K,V> loHead = null, loTail = null; //保存在原索引的链表

  41.                    Node<K,V> hiHead = null, hiTail = null; //保存在新索引的链表

  42.                    Node<K,V> next;

  43.                    do {

  44.                        next = e.next;

  45.                        if ((e.hash & oldCap) == 0) { //哈希值与原数组长度进行&操作,为0则在原数组位置,非0则在原数组索引位置+原数组长度

  46.                            if (loTail == null)

  47.                                loHead = e;

  48.                            else

  49.                                loTail.next = e;

  50.                            loTail = e;

  51.                        }

  52.                        else {

  53.                            if (hiTail == null)

  54.                                hiHead = e;

  55.                            else

  56.                                hiTail.next = e;

  57.                            hiTail = e;

  58.                        }

  59.                    } while ((e = next) != null);

  60.                    if (loTail != null) {

  61.                        loTail.next = null;

  62.                        newTab[j] = loHead;

  63.                    }

  64.                    if (hiTail != null) {

  65.                        hiTail.next = null;

  66.                        newTab[j + oldCap] = hiHead;

  67.                    }

  68.                }

  69.            }

  70.        }

  71.    }

  72.    return newTab;

  73. }

hashmap在java8中的改变

  1. hash冲突的时候的单链表在java8中超过阈值会转化为红黑树,优化了查找速度

  2. 在链表插入由头插法改成了尾插法,是由于原本的头插法在扩容时,高并发下会导致链表成环的问题,而尾插法扩容时会保持链表元素的顺序

引用参考 [1]https://blog.csdn.net/u013494765/article/details/77837338 [2]I am CR7的公众号


文章转载自生活不止眼前的代码,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论