HashMap源码分析

101 阅读1分钟

1.前言

无论任何底层框架,本质上都是数据结构的集合,HashMap也是如此,HashMap是key/value形式来存储,底层基于数组,链表,红黑树来存储。

2.源码分析

 2.1 构造器代码分析   
    public HashMap() {  
        //默认的负载因子,主要用于扩容判断,下文会提及  
        this.loadFactor = DEFAULT_LOAD_FACTOR;
    }  
2.2 将值添加进HashMap
    public V put(K key, V value) {
        //先计算Hash值
        return putVal(hash(key), key, value, false, true);
    }
2.3 进入putVal的代码,先看下存储的
   final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        //HashMap真正存储的数据
        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;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }