HashMap源码分析-基于jdk1.8
程序员文章站
2022-06-04 19:23:22
...
HashMap
- 初始化
描述 Hashmap构造方法一公共有4个,分别如下
/**
* 无参构造
*/
public HashMap() {
//默认的加载因子 0.75
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
/**
* 给定初始容量
* @param initialCapacity
*/
public HashMap(int initialCapacity) {
/*指定集合初始容量 加载因子按照默认的来 0.75f*/
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
* 指定初始容量和加载因子
* @param initialCapacity
* @param loadFactor
*/
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);
}
/**
* 基于已有的集合构建
* @param m
*/
public HashMap(Map<? extends K, ? extends V> m) {
/*默认的加载因子*/
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
2.添加元素
描述 相对于查找来说要复杂很多
/**
* 获取key的hash值
* @param key
* @return
*/
static final int hash(Object key) {
int h;
//key为null时 hash值为0 取key对应的hashcode 异或上 h无符号右移16位,为了防止实现较差的hashcode
// 产生较大的碰撞概率,这里会对hash值做一个移位,让自己的高位和低位做异或,以此来加大hash值得随机性
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
/**
* 在map中加入元素
* @param key
* @param value
* @return
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
*
* @param hash 元素的hash值
* @param key 添加的数据的key
* @param value 添加的数据的值
* @param onlyIfAbsent 是否覆盖已存在的value
* @param evict
* @return
*/
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)
//加入第一个元素的时候,需要初始化下
n = (tab = resize()).length;
/*这种情况说明数组对应的位置还没有数据,没有出现hash碰撞 直接将元素存入即可*/
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
/*进来说明数据已经在数组这个位置发生了碰撞,需要将元素添加到链表或者红黑树中*/
Node<K,V> e; K k;
/*这种说明存在相同的key,需要对旧值做是否覆盖处理*/
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
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) // -1 for 1st
treeifyBin(tab, hash);
break;
}
/*key已存在则退出,对value做是否覆盖处理*/
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
/*e不为空说明key已经存在*/
if (e != null) { // existing mapping for key
V oldValue = e.value;
/*如果onlyIfAbsent为false 则可以将新值覆盖旧值*/
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
/*元素个数超过阈值 则需要扩容*/
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
//重新计算数组大小
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
//如果旧的容量大于0
if (oldCap > 0) {
//如果容量值大于最大容量值,则将阈值设置为最大值
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
//无法扩容啦 直接返回旧的数组
return oldTab;
}
//设置新的容量为原容量的两倍 如果扩容两倍小于最大值,且 旧的值大于出事默认值 则设置新的threshold为旧值得两倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
//设置旧的阈值为新的容量
newCap = oldThr;
else {
// zero initial threshold signifies using defaults
//初始化为默认的容量与阈值 16 ,12
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;
//初始化一个新容量的数组
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
//如果是多线程 这里肯定有问题 将新的数组赋值给数据存储的table
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)
//最简单的情况,没有后续的碰撞元素,直接赋值即可,rehash
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
//如果是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;
}
/*构造一个链表节点的构造函数*/
Node(int hash, K key, V value, Node<K,V> next) {
/*key对应的hash值*/
this.hash = hash;
/*key*/
this.key = key;
/*value*/
this.value = value;
/*后继节点*/
this.next = next;
}
3.查找元素
描述
4.移除元素
描述
/**
* 查找元素
* @param key
* @return
*/
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
/**
* Implements Map.get and related methods
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
/*数组不为空 并且 数组长度大于零 并且 根据hash算法定位到的数组内的链表的头元素不为空*/
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
/*首节点是key对应的值则直接返回*/
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;
}
4.移除元素
描述 相对于查找来说要复杂很多,但是不需要考虑扩容
/**
* Removes the mapping for the specified key from this map if present.
*
* @param key key whose mapping is to be removed from the map
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
/**
* Implements Map.remove and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to match if matchValue, else ignored
* @param matchValue if true only remove if value is equal
* @param movable if false do not move other nodes while removing
* @return the node, or null if none
*/
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
/*数组不为空 并且 数组长度大于零 并且 根据hash算法定位到的数组内的链表的头元素不为空*/
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
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 TreeNode)
node = ((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);
}
}
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode)
/*从红黑树中移除节点*/
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p)
/*如果移除的是头结点,则将数组中元素指向移除元素的后继节点*/
tab[index] = node.next;
else
/*将移除节点的前驱节点的后继节点设置为移除节点的后继节点*/
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
上一篇: HashMap相关知识