1.hash()方法:
hash()方法做了什么
key.hashCode是返回的是地址值,如果key没重写hashCode时候,重写了调用的是自己的,hash方法将hashCode的高16位与低16位异或运算得到的值,这样能充分运用到高16位
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
2.get(Object key)
//如果没有就返回null
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
getNode(int hash, Object key)
first = tab[(n - 1) & hash]干什么用?
n为表的长度,n-1为该结点表中最大索引下标,通过(n-1)&hash得到他所处tab表的位置,也可以理解成桶的下标
getNode做了什么
- 先通过tab[(n - 1) & hash] 定位到表中的位置(或者理解为对应的哪个桶),如果此位置为空直接进不来if包裹的语句返回null
- 此位置不空,比较传过来的hash和此位置第一个元素的hash值,如果hash值相同且对(key==比较相同或调用key的equals方法比较相同直接返回这个位置第一个元素)
- 如果这个if没进去,e取first的下一个元素,同时判断first是不是树,是树的话从树中找这个节点,
- 如果不是树开始do while循环不断判断,先盘判断hash值是否相同,再调(key==比较相同或调用key的equals方法比较相同直接返回这个位置第一个元素) 只要括号中一个成立就返回该结点
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) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
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;
}
3. put(K key, V value)
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/***
*
* @param hash hash值
* @param key 指定的key
* @param value 指定参数value
* @param onlyIfAbsent 如果为true,即使指定参数key在map中已经存在,也不会替换value
* @param evict 如果为false,数组table在创建模式中
* @return 如果value被替换,则返回旧的value,否则返回null。当然,可能key对应的value就是null
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
HashMap.Node<K,V>[] tab; HashMap.Node<K,V> p; int n, i;
//如果哈希表为空,调用resize()方法扩容
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//找到对应的桶位 如果该桶中没有元素就创建个节点放进去
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
//如果该桶中有元素,就先去比较看是否有这个key
else {
HashMap.Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p; //找到的桶中第一个就是要找的 情况
else if (p instanceof TreeNode) //判断这个桶中结点是否转为红黑树
e = ((HashMap.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); //jdk7用头插法放在原来链表前面 8尾插法放后面
//如果当前p是第8个节点点时候,
// 他的binCount=7,刚插入一个元素刚好节点数大于8 那么就开始转红黑树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//如果存在该key ,找到就把改结点赋值给p
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e; //相当于p往链表下走了一个
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value; //原来的值
if (!onlyIfAbsent || oldValue == null)
e.value = value; //需要改的时候更换,如果onlyIfAbsent 为true且oldValue有值就不该
// 访问后回调
afterNodeAccess(e);
return oldValue; //返回原来的值
}
}
//如果里面没有key,再前面添加了个结点,那么下面的逻辑会被执行,
// 更新结构化修改信息
++modCount; //如果是找到key修改信息这个值不会加,因为不会运行到这里
//size大小大于要阈值时候进行扩容
if (++size > threshold)
resize();
// 插入后回调,为LinkedHashMap服务的
afterNodeInsertion(evict);
return null;
}
4. resize() 扩容
final HashMap.Node<K,V>[] resize() {
HashMap.Node<K,V>[] oldTab = table;
//算出没扩容前哈希表的大小
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold; //没扩容器那的阈值
int newCap, newThr = 0;
if (oldCap > 0) { //如果原来哈希表长度大于0
if (oldCap >= MAXIMUM_CAPACITY) { //容量大于1<<30次方时候
threshold = Integer.MAX_VALUE; //直接将阈值设置为整形的最大值 2的31次方-1
return oldTab; //无法扩容,返回原来的数组
}
//原来现在容量扩大两倍小于最大值,且原来容量大于初始值
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold 新的阈值扩大为原来的2倍
}
//如果旧容量<=0 且阈值(临界值)>0时候
else if (oldThr > 0) // initial capacity was placed in threshold
// 数组的新容量设置为老数组扩容的临界值
newCap = oldThr;
//如果旧容量 <= 0,且旧临界值 <= 0,新容量扩充为默认初始化容量,新临界值
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY; //16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); //12
}
//在当上面的条件判断中,只有oldThr > 0成立时,newThr == 0,只有这一步没有对newThr进行赋值
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
//&&左右都为true的时候才返回ft
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
//将扩容后hashMap的临界值设置为newThr
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
HashMap.Node<K,V>[] newTab = (HashMap.Node<K,V>[])new HashMap.Node[newCap];
table = newTab;
if (oldTab != null) {
//遍历旧哈希表的每个桶,将旧哈希表中的桶复制到新的哈希表中
for (int j = 0; j < oldCap; ++j) {
HashMap.Node<K,V> e;
//如果旧桶不为null,使用e记录旧桶
if ((e = oldTab[j]) != null) {
//将旧桶置为null
oldTab[j] = null;
//如果旧桶中只有一个node
if (e.next == null)
//将e也就是oldTab[j]放入newTab中e.hash & (newCap - 1)的位置
newTab[e.hash & (newCap - 1)] = e;
//如果旧桶中的结构为红黑树
else if (e instanceof HashMap.TreeNode)
//将树中的node分离
((HashMap.TreeNode<K,V>)e).split(this, newTab, j, oldCap);
//如果旧桶中的结构为链表,链表重排,jdk1.8做的一系列优化
else { // preserve order
HashMap.Node<K,V> loHead = null, loTail = null;
HashMap.Node<K,V> hiHead = null, hiTail = null;
HashMap.Node<K,V> next;
do {
next = e.next;
//就是区分新增的那一位是否等于0如果是就是原索引,不是就是原索引加oldcap
if ((e.hash & oldCap) == 0) {
if (loTail == null) //尾是空的,说明还没有元素构建成链表,开始构建你第一个
loHead = e;
else
loTail.next = e;
loTail = e;
}
//等于1的时候
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; //更新哈希表j位置为该链表(新增的1位为0的)
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead; //把j+原表长度位置更新为新建的链表
}
}
}
}
}
return newTab;
}
5.treeifyBin(省略)
将链表转化为红黑树
final void treeifyBin(HashMap.Node<K,V>[] tab, int hash) {
int n, index; HashMap.Node<K,V> e;
//如果哈希表为空,或者小于转化树时候最小容量将进行扩容
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();//扩容
// 如果符合转化为红黑树的条件,而且hash对应的桶不为null
else if ((e = tab[index = (n - 1) & hash]) != null) {
// 红黑树头结点 红黑树尾结点
HashMap.TreeNode<K,V> hd = null, tl = null;
do {
//替换链表node为树node,建立双向链表
HashMap.TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
//遍历链表插入每个节点到红黑树
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
6. putAll(省略)
将参数map中的所有键值对映射插入到hashMap中,如果有碰撞,则覆盖value。
public void putAll(Map<? extends K, ? extends V> m) {
putMapEntries(m, true);
}
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
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)
//更新临界值为大于该t的最小的数 且是2的幂 这个和调用hashmap有参构造器中最后一句代码一样
threshold = tableSizeFor(t);
}
else if (s > threshold)
resize(); //扩容
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);
}
}
}
7. 说一说threshold
如果你new hashMap构造时候没有传初始容量,threshold一直是0,new带参数的构造器,他会让threshold为大于initialCapacity等于他的最小的数且是2的整数幂,没指定初始大小时候,当调用put方法的时候会执行这段代码,初始化容量为16 阈值为12.
newCap = DEFAULT_INITIAL_CAPACITY; newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
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);
}
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
如果你构造hashMap传有初始化容量,
构造时候会让阈值等于初始化容量
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);
}
那么第一次扩容时候,会让容量设置为阈值
newCap = oldThr;
同时加载因子重新变为该容量3/4(也可以是指定的加载因子) 在容量不超过MAXIMUM_CAPACITY
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
8.remove(Object key))
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
final HashMap.Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
HashMap.Node<K,V>[] tab; HashMap.Node<K,V> p; int n, index;
//对应桶中有元素进入if
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
//node为移除的结点
HashMap.Node<K,V> node = null, e; K k; V v;
//第一个节点就是的要移除的时候
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
//如果对应的桶中是以红黑树结构存在的
if (p instanceof HashMap.TreeNode)
//找到该结点
node = ((HashMap.TreeNode<K,V>)p).getTreeNode(hash, key);
else { //是以链表形式存在的
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null); //找到要移除的结点,没有的时候e==null跳出循环
}
}
//如果得到的node不为null且(matchValue为false||node.value和参数value匹配)
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof HashMap.TreeNode) //节点是树节点
//移除该界限
((HashMap.TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p) //该结点是头结点 相等说明就是只有一个节点
tab[index] = node.next;
else
p.next = node.next; //或者让改p节点指向删除结点的下一个节点
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
//表为空 或者hash映射到桶为空 时候返回null
return null;
}
9.clear()
public void clear() {
Node<K,V>[] tab;
modCount++;
if ((tab = table) != null && size > 0) {
size = 0;
for (int i = 0; i < tab.length; ++i)
tab[i] = null;
}
}