数据结构
1、HashMap由数组、链表、红黑树组成
2、当两个或以上的key相同且key值不同时(发生冲突),就会挂在数组初始化后的链表后
3、当某个节点后出现过多链表节点(8),就会转换成红黑树。
源码分析
通过新增(put)、查询(get)、删除(remove)深度剖析hashMap源码
1、创建Map实例
HashMap<String, String> map = new HashMap<>();
2、跟踪构造函数
public HashMap() {
//初始化载荷系数
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
static final float DEFAULT_LOAD_FACTOR = 0.75f;//载荷系数为0.75
3、插入数据 put()
map.put("hello","world");
4、跟踪put()方法
public V put(K key, V value) {
//hash(key)详见4.1
return putVal(hash(key), key, value, false, true);
}
4.1、跟踪hash()方法
static final int hash(Object key) {
int h;
//hashCode后 右移16位异或处理,增加散列度
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
5、跟踪putVal()方法
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//transient Node<K,V>[] table; table初始化为空
if ((tab = table) == null || (n = tab.length) == 0)
//resize()函数见5.1说明 返回初始化数组的长度
n = (tab = resize()).length;
//如果数组容量-1(即n-1)与hash值进行与运算后为空,说明该下标位置没有数据
if ((p = tab[i = (n - 1) & hash]) == null)
//直接插入数据
tab[i] = newNode(hash, key, value, null);
else {
//否则说明该下标位置有数据
Node<K,V> e; K k;
//p = tab[i = (n - 1) & hash]
//如果该下标位置的key和传入的key值相同,e=p
//先比较hash的好处:hash值不同的key值一定不同,节省运算比较的时间
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//如果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);
//红黑树阈值 8,即单链表节点数超过8个转换成红黑树
//static final int TREEIFY_THRESHOLD = 8;
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
//使用树函数
treeifyBin(tab, hash);
break;
}
//判断单链表中是否存在相同的key值
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
//临时节点,方便遍历
p = e;
}
}
//存在key值相同的情况,修改value值
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
//如果数组容量大于阈值(),进行2倍扩容
if (++size > threshold)
//resize()详见5.1
resize();
afterNodeInsertion(evict);
return null;
}
5.1 resize()函数剖析
resize()函数在初始化和扩容的时候都调用
final Node<K,V>[] resize() {
//初始化table为空,扩容时为原数组
Node<K,V>[] oldTab = table;
//原容量
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//初始化阈值容量
int oldThr = threshold;
int newCap, newThr = 0;
//如果原容量大于零
if (oldCap > 0) {
//static final int MAXIMUM_CAPACITY = 1 << 30;
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//oldCap<<1 相当于原容量2倍
//static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
//新的阈值也2倍扩容
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
//原容量为0,即初始化
else { // zero initial threshold signifies using defaults
//static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
//初始化数组容量为16
newCap = DEFAULT_INITIAL_CAPACITY;
//初始化阈值为0.75*16 =12
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"})
//创建一个新的map容器
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
//如果原数组不为空,即扩容时需要将原数组数据插入到新map容器中
if (oldTab != null) {
//遍历原数组
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
//如果该数组下标位置只有一个元素
if (e.next == null)
//直接插入到新map中
newTab[e.hash & (newCap - 1)] = e;
//如果该数组下标位置是树节点
else if (e instanceof 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;
//插入到原下标+oladCap位置,与新容量-1 & hash 相同
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
6、get()方法
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) {
//判断是否只有一个元素
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;
}
7.remove()方法
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
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;
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;
//判断当前节点是否只有一个元素,借助临时节点node
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保存node的前一个节点
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;
}
8、序列化writeObject()
private void writeObject(java.io.ObjectOutputStream s)
throws IOException {
//初始化容量
int buckets = capacity();
// Write out the threshold, loadfactor, and any hidden stuff
s.defaultWriteObject();
s.writeInt(buckets);
//size为实际节点数
s.writeInt(size);
internalWriteEntries(s);
}
总结:
1、数组容量为2的倍数
①提高运算 速度
②增加散列度,降低冲突
③减少内存碎片
2、hash函数与pos定位
hashCode与右移16后进行异或,增加散列度,降低冲突
3、插入冲突
通过单链表解决冲突,如果链表长度超过8,单链表转换成红黑树提高查询速度
4、扩容
扩容条件:实际节点数大于容量的四分之三
扩容后数据排布:要么是原下标的位置,要么是原下标+原容量的位置。
5、序列化
只存储了数组的容量、实际节点数量和各节点的key、value值