HashMap原理

2020-01-03  本文已影响0人  leap_
本文参考:

HashMap的扩容机制---resize()
HashMap的扩容及树化过程

HashMap的内部是使用Hash表来存储数据的;


Hash表

Hash表是数组和链表的组合,存储的数据会放在粉色节点中

概念介绍:

    transient Node<K,V>[] table;
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;
......
    }
    /**
     * The number of key-value mappings contained in this map.
     */
    transient int size;
    /*
     * The load factor for the hash table
     */
    final float loadFactor;

    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    /**
     * The next size value at which to resize (capacity * load factor).
     *
     * @serial
     */
    // (The javadoc description is true upon serialization.
    // Additionally, if the table array has not been allocated, this
    // field holds the initial array capacity, or zero signifying
    // DEFAULT_INITIAL_CAPACITY.)
    int threshold;

put()

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

//   传入 key value key的hashcode 
    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;
        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);
                        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;
// 如果size超过了threshold也要进行resize()
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

第一次添加数据table == null , 调用resize()

resize() —— 新建数组

    final Node<K,V>[] resize() {
......
        newCap = DEFAULT_INITIAL_CAPACITY;  //  数组默认大小 16 
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
......
    }

创建一个新的默认大小是16的数组;然后回到putVal(),因为是新建的数组,所以肯定是空的,直接放到数组中;如果当前数组下标不会空,就以当前元素为头节点,放到链表中,如果size超过了threshold也要进行resize()

resize() —— 数组扩容

    final Node<K,V>[] resize() {
......
            newCap = oldCap << 1   //  16 左移一位 变 32 
            newCap = oldThr;
//   新的数组大小是32 
            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;
                        }
                    }
                }
            }
        }
        return newTab;
    }

当size超过threshold时,添加的数据会大概率的碰撞(Hash冲突),导致链表的数量增加,遍历链表会降低效率,而增加数组的容量会导致大量的空间浪费,负载因子是典型的时空转化问题,用空间换时间;

get()

get操作先通过key获取到数组的下标index,再遍历这个链表当key等于节点的key时就取到这个值了;

数组的查询很快是o(1),链表的查询是o(n),如果链表过长,查询就会慢,如果数组过长,可能会造成空间浪费,loadfactor默认是0.75,默认容量是16,如果元素超过threshHold(loaderfactor*capacity)就会进行resize扩容,至于为什么是0.75 和 16,hash的计算是经过位运算,0.75和16可以做到最科学的均匀分布

HashMap树化

链表长度大于8,数组长度大于64,就会把链表转为红黑树;

面试相关的问题

1. HashMap的实现,工作原理?
2. 如果两个key的HashCode相同,会出现什么情况
3. 数组扩容以后会出现什么问题?
4. 为什么使用String和Integer这样的包装类作为key?
5. 可以用自定义的类作为key吗?
6. 如果HashMap的数量超过负载因子的大小会干什么?
上一篇 下一篇

猜你喜欢

热点阅读