HashMap 源码查看记录

一、map结构

public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {

//所能容纳的key-value对极限
int threshold;

//负载因子
final float loadFactor;

//记录修改次数
int modCount;

//实际存在的键值对数量
int size;

//哈希桶数组
transient Node<K,V>[] table;
}

二、节点

static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;//hash值
        final K key;//k键
        V value;//value值
        Node<K,V> next;//链表中下一个元素
}

三、计算hash值及数组下标

/**获取hash值方法*/
static final int hash(Object key) {
     int h;
     // h = key.hashCode() 为第一步 取hashCode值(jdk1.7)
     // h ^ (h >>> 16)  为第二步 高位参与运算(jdk1.7)
     return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);//jdk1.8
}
/**获取数组下标方法*/
static int indexFor(int h, int length) {
    //jdk1.7的源码,jdk1.8没有这个方法,但是实现原理一样的,jdk8在put时计算

    /**
    * 通过h & (table.length -1)来得到该对象的保存位,而HashMap底层数组的长度总是2的n次方,这是HashMap在速度上的优化。
    * 当length总是2的n次方时,h& (length-1)运算等价于对length取模,也就是h%length,但是&比%具有更高的效率。
    */   

    return h & (length-1); //第三步 取模运算

}

四、put源码及过程详解

 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)    //判断键值table是否为空
            n = (tab = resize()).length;          //为空则扩容
         
        if ((p = tab[i = (n - 1) & hash]) == null)  //i = (n - 1) & hash重新计算hash,tab[i]为空,直接新增节点
            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))))  //判断tab[i]首元素是否与key相同,相同则覆盖
                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) // 节点数超过8,转换为红黑树
                            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;
    }  

 文字说明

  • 1、判断键值对数组 table[i]是否为空或为 null,否则执行 resize()进行扩容;

  • 2、根据键值 key 计算 hash 值得到插入的数组索引 i,如果 table[i]==null,直接新建节点添加;

  • 3、当 table[i]不为空,判断 table[i]的首个元素是否和传入的 key 一样,如果相同直接覆盖 value;

  • 4、判断 table[i] 是否为 treeNode,即 table[i] 是否是红黑树,如果是红黑树,则直接在树中插入键值对;

  • 5、遍历 table[i],判断链表长度是否大于 8,大于 8 的话把链表转换为红黑树,在红黑树中执行插入操作,否则进行链表的插入操作;遍历过程中若发现 key 已经存在直接覆盖 value 即可;

  • 6、插入成功后,判断实际存在的键值对数量 size 是否超多了最大容量 threshold,如果超过,进行扩容操作;

  

posted @ 2019-10-12 14:10  pu_xb  阅读(300)  评论(0编辑  收藏  举报