HashMap源码解读

常量解释

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; //默认初始容量,1<<4 意思是1的二进制左移4位,等于 1*2^4=16
static final int MAXIMUM_CAPACITY = 1 << 30; //最大容量,1左移30位,等于 1*2^30 

static final float DEFAULT_LOAD_FACTOR = 0.75f;//默认负载因子

static final int TREEIFY_THRESHOLD = 8;//树型化阀值,当链表长度超过8,转红黑树

static final int UNTREEIFY_THRESHOLD = 6;//树转链表阀值

static final int MIN_TREEIFY_CAPACITY = 64;//树形化最小表容量

//带参构造器,指定初始容量和负载因子
public HashMap(int initialCapacity, float loadFactor) {
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);
}
//带参构造器,指定初始容量
public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
//无参构造器,默认初始容量16,负载因子0.75
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
//带参构造器,参数为map
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}

//详解put方法
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}
//key.hashCode() 取key的hashCode
//h >>> 16 对key的hashCode做 无符号右移16位运算,为啥做无符号右移16位,是因为一般hashCode值都在2^32以内,做无符号右移16位,可以取到32位二进制中的高16位,
//后续hashcode和hashcode的高16位做 异或运算的时候,使得key的存储位置更加分散,减少hash冲突
// hashcode和 hashcode高16位做异或运算,为啥做异或,而不是与运算或者或运算,因为与、或运算后,结果都偏向0

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;
if ((tab = table) == null || (n = tab.length) == 0)//当map中node数组为null或者长度为0,则初始化一个node数组
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null) //根据上面hash()计算的hash值跟数组长度做与运算,相当于对hash % length 取余,(此处设计很巧妙,(n-1)& hash == hash % n,是因为n长度设计为2的n次幂)
                              再根据取余结果去table中取值,如果为null,则直接存储在table中
        tab[i] = newNode(hash, key, value, null);
else {                        //如果table[hash()%(n-1)]位置不为空,则继续处理
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k)))) //如果入参和node里的key相等,并且hash值也一致,则取出node,后续直接替换node的value
e = p;
else if (p instanceof TreeNode)         //判断node的数据类型属于树,如果是,则往数中添加value
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {                       //如果不是树,则遍历链表
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {      //如果链表下个节点为null,则直接new一个新的node,存储在尾端
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st//如果此时链表长度 = 树形化阀值(默认8),则树化
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) //如果链表中存在hash、key一致的,则取出元素,后续替换元素的value
break;
p = e;
}
}
if (e != null) { // existing mapping for key //此处e就是table中key和hash一致的取出的元素,此处替换该元素的value
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold) //判断实际存储元素数量 是否大于 扩容阀值(容量*负载因子),大于则触发扩容
resize();
afterNodeInsertion(evict);
return null;
}

//详解get方法,hash()和上面get中的hash()方法一样,做key做hash运算
public V get(Object key) {
    Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}


final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {  //table不为空,并且table[hash%(n-1)]获取的元素不为空,n是数组长度
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))//如果取出node的hash和key与入参一致,则直接返回node
return first;
if ((e = first.next) != null) {                    //如果不一致,并且node的next元素不为空
if (first instanceof TreeNode)                  //再判断node类型是否为树
return ((TreeNode<K,V>)first).getTreeNode(hash, key);  
do {                                  //不为树,则遍历链表
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
 


















原文地址:https://www.cnblogs.com/wenhuang/p/13509345.html