HashMap源码分析

72 阅读3分钟

直接进入正题,先看该类的属性

//默认初始化的容量 16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; 

 //默认最大的容量。必须是2的冥
static final int MAXIMUM_CAPACITY = 1 << 30;

 //构造函数中未指定时使用的负载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;

//节点转换成树的阈值
static final int TREEIFY_THRESHOLD = 8;

 //节点减少成链表的阈值
static final int UNTREEIFY_THRESHOLD = 6;

//
transient Node<K,V>[] table;

 //键值对的数量
transient int size;

/**
 * The number of times this HashMap has been structurally modified
 * Structural modifications are those that change the number of mappings in
 * the HashMap or otherwise modify its internal structure (e.g.,
 * rehash).  This field is used to make iterators on Collection-views of
 * the HashMap fail-fast.  (See ConcurrentModificationException).
 */
transient int modCount;

//下一次扩容的值(capacity * load factor)
int threshold;

 //加载因子
final float loadFactor;

通过上面的属性,能发现,hashMap是一个Node数组,那么接下来看Node类的属性

static class Node<K,V> implements Map.Entry<K,V> {

    final int hash;
    final K key;
    V value;
    
    //下一个Node,形成了一个链表的关系
    Node<K,V> next;

    Node(int hash, K key, V value, Node<K,V> next) {
        this.hash = hash;
        this.key = key;
        this.value = value;
        this.next = next;
    }
    .....
 }

在来看构造函数

//无参构造函数
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

//指定初始化容量的参数。默认的加载因子0.75
public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

//指定初始化容量与加载因子
public HashMap(int initialCapacity, float loadFactor) {

    //如果指定的初始化容量小于了0,抛异常
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
     
    //如果指定的初始化容量大于了最大值,则使用最大的容量值                                   
    if (initialCapacity > MAXIMUM_CAPACITY)
        initialCapacity = MAXIMUM_CAPACITY;
      
    if (loadFactor <= 0 || Float.isNaN(loadFactor))
        throw new IllegalArgumentException("Illegal load factor: " +
                                           loadFactor);
    this.loadFactor = loadFactor;
    
    //返回给定目标容量的两个大小的幂
    this.threshold = tableSizeFor(initialCapacity);
}

接下来查看,往HashMap中添加数据的时候,执行的代码

//往map中存放数据,先计算key的 hash值
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

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

//重点
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    
    //如果table 为空,则先进行扩容
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
        
    //通过key的hash与table的数组大小进行与运算,确定该key的位置,
    //如果该位置为空,则创建一个node,并赋值
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        
        //如果存放的key的hash值与该位置node的key的hash相同并且key值也相同
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
            
        //如果该位置的node是一个TreeNode    
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
        
            //进行一个for的死循环
            for (int binCount = 0; ; ++binCount) {
            
                 //通过一个node节点找下一个node,如果下一个node为空
                if ((e = p.next) == null) {
                
                    //生成一个新的node,放在该node的下一个
                    p.next = newNode(hash, key, value, null);
                    
                    //如果该node链表中的数量大于等于了8
                    if (binCount >= TREEIFY_THRESHOLD - 1) 
                        treeifyBin(tab, hash);//转换成树
                        
                    //跳出循环    
                    break;
                }
                
                //如果该node与存放的key的hash相同,并且key值也相同,跳出循环
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                    
                //通过for循环,挨个查找下个node
                p = e;
            }
        }
        
        //如果e不等于空,表示map中存在已有相同的key
        if (e != null) { 
            //获取原来的value值
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value; //新的vlue值替换原有的value值
                
            //LinkedHashMap post操作的回调(hashMap中是空操作)    
            afterNodeAccess(e);
            return oldValue;//返回原来的value值
        }
    }
    
    //修改次数加一
    ++modCount;
    
    //如果当前的键值对数量大于了需要扩容的值(capacity * load factor),则进行扩容
    if (++size > threshold)
        resize();
        
    //空操作不用理会    
    afterNodeInsertion(evict);
    return null;
}

下面则查看resize 方法的代码

final Node<K,V>[] resize() {
    Node<K,V>[] oldTab = table;
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    int oldThr = threshold;
    int newCap, newThr = 0;
    if (oldCap > 0) {
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        //如果table的容量小于最大容量,并且大于默认的初始容量,则扩容阈值变成两倍
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
            newThr = oldThr << 1; // double threshold
    }
    else if (oldThr > 0) // initial capacity was placed in threshold
        newCap = oldThr;
    else {               // zero initial threshold signifies using defaults
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    //如果扩容阈值为0,则设置值
    if (newThr == 0) {
        float ft = (float)newCap * loadFactor;
        newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                  (int)ft : Integer.MAX_VALUE);
    }
    threshold = newThr;
    
    Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    //将扩容后的table赋值给原来的table
    table = newTab;
    
    if (oldTab != null) {
        //将原来的table中的值,存放到新的table中
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;
                //如果为空,表示该node链表上只有一个node
                if (e.next == null)
                    //将该node进行hash重新定位到新的table中
                    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;
}