##Hash和java渊源 1.所有的类都继承自Object,而Object有hashCode,也就是所有的类均有hashCode 方法
2.重写equals方法必须重写hashCode方法 ##HashMap Hash的数据结构 ###HashMap的数据结构
- table:HashMap.Node的数组,存储节点
- entrySet:node的结合
- size:Map的大小
- modCount:修改次数
- threshold:阀值
- loadFactor:加载因子
hashMap的节点是Node,Node的数据结构如下
- hash:hashCode
- next:下一节点
- key:key
- value:value
###HashMap方法 ###put方法 put方法主要是调用putVal putVal中有个参数evict,evict主要是用于决定排序的基数,用于LinkedHashMap
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//如果hashMap为空,分配空间
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//根据hashCode计算节点位置,并存储Node
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; //如果已存在Key则覆盖之前的Node
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
//找到hashCode下最后的一个节点
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;
}
}
//修改次数+1
++modCount;
//超过阀值重写分配
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
###putAll putAll就是调用putMapEntries。evict和putVal中一样
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
//table为空重新计算大小
if (table == null) { // pre-size
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
threshold = tableSizeFor(t);
}
//超过阀值
else if (s > threshold)
resize();
//遍历Entry,调用putVal
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
putVal(hash(key), key, value, false, evict);
}
}
}
###computeIfAbsent,computeIfPresent,putIfAbsent computeIfAbsent和computeIfPresent都是java8之后出现的