为什么会出现hashmap?
数组:每次插入的时候都是复制再进行插入 十分的耗费性能
链表:包含此节点和下一个节点的内存地址 只能通过头结点开始循环遍历
综合数组和链表 :散列表
数组+链表+红黑树
数组长度大于64 (总的数据量) 链表长度大于8,链表就会升级成红黑树。
Put数据的过程:
1、我们要插入 (key,value)
2、计算key的hash值 并经过扰动函数 使hash更加散列
3、构造出一个Node实例 包括 (hash值、Key、value、next)
4、路由寻址 找出node应该存放的位置 路由寻址函数(table.length-1 & node.hash)Hash碰撞
hash相同的时候 需要在相同的位置进行链表的插入
扩容阈值
static final int tableSizeFor(int cap) {
int n = cap - 1; //目的是为了计算出来的结果是2的n次方。 因为2的幂-1都
是11111结尾的,所以碰撞几率小。
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
Put源码分析
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/
* 在往haspmap中插入一个元素的时候,由元素的hashcode经过一个扰动函数之后再与table的长度进行与运算才找到插入位置,下面的这个hash()方法就是所谓的扰动函数
* 作用:让key的hashCode值的高16位参与运算,hash()方法返回的值的低十六位是有hashCode的高低16位共同的特征的
* 举例
* hashCode = 0b 0010 0101 1010 1100 0011 1111 0010 1110
*
* 0b 0010 0101 1010 1100 0011 1111 0010 1110 ^
* 0b 0000 0000 0000 0000 0010 0101 1010 1100
* 0b 0010 0101 1010 1100 0001 1010 1000 0010
*/
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) {
// tab表示当前hashmap的table
// p表示table的元素
// n表示散列表的长度
// i表示路由寻址结果
Node<K,V>[] tab; Node<K,V> p; int n, i;
// 延迟初始化逻辑,第一次调用putval()方法的时候才进行初始化hashmap中最耗内存的talbe
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 1.最简单的一种情况,寻找到的桶位,刚好是null,这个时候直接构建Node节点放进去就行了
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
// e,如果key不为null,并且找到了当前要插入的key一致的node元素,就保存在e中
// k表示一个临时的key
Node<K,V> e; K k;
// 2.表示该桶位中的第一个元素与你当前插入的node元素的key一致,表示后序要进行替换操作
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 3.表示当前桶位已经树化了
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
// 4.当前捅位是一个链表
else {
for (int binCount = 0; ; ++binCount) {
// 4.1 迭代到最后一个元素了也没有找到要插入的key一致的node
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// 4.1 找到了与要插入的key一致的node元素
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// 如果找到了与要插入的key一致的node元素,那么进行替换
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
// nodeCount表示散列表table结构的修改次数,替换Node元素的value不算
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
扩容操作
当在table长度位16中的元素移到table长度位32的table中的时候;我们可以知道,原来在15这个槽位的元素的hash()值的后四位一定是1111(因为跟1111即table长度-1 进行与运算得到了1111)。所以所以当table长度变为32的时候,原来在15这个槽位的元素要么还在15这个槽位,要么在31这个操作(因为原来15这个槽位的元素后五位一定是11111或者01111,跟 11111即table新长度-1 进行与运算一定得到 01111或者11111)
扩容源码
/**
* 对table进行初始化或者扩容。
* 如果table为null,则对table进行初始化
* 如果对table扩容,因为每次扩容都是翻倍,与原来计算(n-1)&hash的结果相比,节点要么就在原来的位置,要么就被分配到“原位置+旧容量”这个位置。
*/
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
// oldCap表示扩容之前table数组的长度
int oldCap = (oldTab == null) ? 0 : oldTab.length;
// oldThr表示本次扩容之前的阈值,触发本次扩容操作的阈值
int oldThr = threshold;
// newCap:表示扩容之后table数组的大小; newThr表示扩容之后,下次出发扩容的条件
int newCap, newThr = 0;
//===================给newCap和newThr赋值start=============================
// oldCap大于零,说明之前已经初始化过了(hashmap中的散列表不是null),要进行正常的扩容操作
if (oldCap > 0) {
// 已经最大值了,不再扩容了
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// (1)进行翻倍扩容(假如旧的oldCap为8, < DEFAULT_INITIAL_CAPACITY,那么此条件不成立newThr将不会赋值)
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
// (2)
// oldCap == 0(说明hashmap中的散列表是null)且oldThr > 0 ;下面几种情况都会出现oldCap == 0,oldThr > 0
// 1.public HashMap(int initialCapacity);
// 2.public HashMap(Map<? extends K, ? extends V> m);并且这个map有数据
// 3.public HashMap(int initialCapacity, float loadFactor);
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
// oldCap == 0, oldThr == 0
// public HashMap();
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
// 对应上面(1)不成立或者(2)成立的情况
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
//===================给newCap和newThr赋值end=============================
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
// 头结点不为空
if ((e = oldTab[j]) != null) {
// 将对应的桶位指向null,方便jvm回收
oldTab[j] = null;
// 1.如果只有一个节点
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
// 2.树化了
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
// 3.还是链表
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;
// 比如e.hash只能为两种可能 1 1111 或者 0 1111 , oldCap 为 10000
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;
}
Get方法源码和Remove源码
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) {
// tab:引用当前hashmap的table
// first:桶位中的头元素
// n:table的长度
// e:是临时Node元素
// k:是key的临时变量
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
// 1.如果哈希表为空,或key对应的桶为空,返回null
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
// 2.这个桶的头元素就是想要找的
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
// 说明当前桶位不止一个元素,可能是链表,也可能是红黑树
if ((e = first.next) != null) {
// 3.树化了
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
// 4.链表
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
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) {
// tab:引用当前hashmap的table
// p:当前的node元素
// n:当前的散列表数组长度
// index:表示寻址结果
Node<K,V>[] tab; Node<K,V> p; int n, index;
// 1.如果数组table为空或key映射到的桶为空,返回null。
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
// node:查找到的结果
// e:当前Node的下一个元素
Node<K,V> node = null, e; K k; V v;
// 2.桶位的头元素就是我们要找的
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
// 3.树化了
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
// 4.链表中
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);
}
}
// 如果node不为null,说明按照key查找到想要删除的数据了
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;
}