HashMap源码

静态常量

/**
 * 默认容量16
 */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;

/**
 * 最大容量
 */
static final int MAXIMUM_CAPACITY = 1 << 30;

/**
 * 默认负载因子
 * 默认情况下当键值对数量大于16 * 0.75 = 12时就会触发第一次扩容
 */
static final float DEFAULT_LOAD_FACTOR = 0.75f;

/**
 * 树化阈值
 * 即链表转成红黑树的阈值,在存储数据时,当链表长度>8时,则将链表转换成红黑树
 */
static final int TREEIFY_THRESHOLD = 8; 

/**
 * 树退化阈值
 * 即红黑树转为链表的阈值,当在扩容(resize())时HashMap的数据存储位置会重新计算,在重新计算存储位置后,当原有的红黑树内数量<6时,则将红黑树转换成链表
 */
static final int UNTREEIFY_THRESHOLD = 6;

/**
 * 最小树形化阈值
 * 在转变成树之前,还会有一次判断,只有键值对数量大于 64 才会发生转换。这是为了避免在哈希表建立初期,多个键值对恰好被放入了同一个链表中而导致不必要的转化
 */
static final int MIN_TREEIFY_CAPACITY = 64;

常用方法

构造方法
public HashMap() {
    // 空参构造函,初始化加载因子为0.75
    this.loadFactor = DEFAULT_LOAD_FACTOR;
}
put(K key, V value)
public V put(K key, V value) {
    // hash(key) 获取key对应的hash,key为空返回0
    return putVal(hash(key), key, value, false, true);
}


/**
 * 实现Map.put及相关方法
 *
 * @param hash hash for key
 * @param key 键
 * @param value 键对应的值
 * @param onlyIfAbsent 如果为true,不更改现有的值
 * @param evict 如果为false,则表处于创建模式
 * @return 返回键对应的值,如果没有则返回null
 */
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)
        //当前实例为null 或 当前实例无数据,通过resize()创建一个长度为16的Node<K,V>数组
        //n为最大下标
        n = (tab = resize()).length;
    
    /*通过最大下标通过 位与运算判断是否哈希冲突,从而判断数据存储方式*/
    if ((p = tab[i = (n - 1) & hash]) == null)
        //hash不冲突,创建一个Node对象放到Node数组
        tab[i] = newNode(hash, key, value, null);
    else {
        //p为当前实例中Hash冲突的数据对象
        //hash冲突,新put仅的
        Node<K,V> e; K k; 
        if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
            //hash与已存在的数据对象hash相同,key与已存在数据对象的key相同(包含null)
            e = p; //e是冲突的数据对象,k是冲突的数据对象的key
        else if (p instanceof TreeNode)
            //与树节点对象hash冲突
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            //与链表中的对象hash冲突
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {
                    //冲突对象的next节点为空,将新进元素以链表的方式放到冲突对象的next节点
                    p.next = newNode(hash, key, value, null);
                    
                    //next节点长度存储达到8-1时,后进元素将采用树的方式存储数据
                    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; // 计算器加1
    if (++size > threshold)
        //新进元素添加成功后,如果超出阈值进行扩容
        resize();
    afterNodeInsertion(evict);
    return null;
}



resize()
/**
 * Initializes or doubles table size.  If null, allocates in
 * accord with initial capacity target held in field threshold.
 * Otherwise, because we are using power-of-two expansion, the
 * elements from each bin must either stay at same index, or move
 * with a power of two offset in the new table.
 *
 * @return the table
 */
final Node<K,V>[] resize() {
    //获取当前实例对象
    Node<K,V>[] oldTab = table;
    
    //获取当前实例对象的数据长度和阈值
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    int oldThr = threshold;  //threshold:阈值=容量*负载系数,数据长度超过此数值就要调整大小
    
    //初始化扩容后的容量和阈值,默认都为0
    int newCap, newThr = 0;

    if (oldCap > 0) {
        if (oldCap >= MAXIMUM_CAPACITY) {
            //当前实例包含元素,数据长度超过1<<30,阈值调整为HashMap支持的最大长度
            threshold = Integer.MAX_VALUE;  //当前实例对象数据长度超过1 << 30,阈值调整为Integer.MAX_VALUE
            return oldTab;
        }
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) 
            //当前容量扩容一倍(<<1)后的数据承载长度不超出1<<30,且当前实例对象数据长度>=16
            //扩容后阈值提高一倍
            newThr = oldThr << 1;
    }
    else if (oldThr > 0)
        //...
        newCap = oldThr; 
    else {
        //当前实例对象处于刚刚被构建的状态时,初始化默认容量为16,初始化阈值为12=16*0.75
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    
    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>说明:
       Node<K,V>是HashMap中的内部类,实现了Map接口的内部接口Entry
       Node<K,V>类中包含一个使用final修饰的key,value 和一个通过key和value异或运算出的使用finale修饰的hash,以及一个空的Node<K,V>对象next
    */
    //根据前面计算出的新的容量创建一个存放元素的数组,并给将实例的引用指向新的数组
    @SuppressWarnings({"rawtypes","unchecked"})
    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; //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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值