hashmap原理
hashmap底层是由数组+链表组成的数据结构
链表长度>8时自动转换为红黑树,当长度<6时自动转换为链表
例如:
put(a)的hash值为2,put(b)的hash值也为2,hash值相同时就会通过equal()比较key值是否相同,key值相同,则覆盖,不相同就会形成链表。
特性
1.HashMap存储键值对实现快速存取,允许为null。key值不可重复,若key值重复则覆盖。
2.非同步,线程不安全。
3.底层是hash表,不保证有序(比如插入的顺序)
成员常量
// 初始大小,默认为16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
// 最大容量为2的30次方
static final int MAXIMUM_CAPACITY = 1 << 30;
// 默认的装载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 链表转换为红黑树的阈值
static final int TREEIFY_THRESHOLD = 8;
// 红黑树转换为链表的阈值
static final int UNTREEIFY_THRESHOLD = 6;
// 链表转红黑树的最小容量
static final int MIN_TREEIFY_CAPACITY = 64;
成员变量
// 存储元素的数组,总是2的幂次倍
transient Node<K,V>[] table;
// 保存entrySet的缓存
transient Set<Map.Entry<K,V>> entrySet;
// 键值对数量
transient int size;
// 修改次数
transient int modCount;
// 阈值,hashmap键值对数量超过阈值,就会扩容;当实际大小(容量*填充因子)超过临界值时
int threshold;
// 负载因子
final float loadFactor;
插入(修改)put()方法
public V put(K key, V value) {
// hash(key)计算key的hash值
return putVal(hash(key), key, value, false, true);
}
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) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// 判断tab是否为null,长度是否为0,初始化hash表的时机为第一次调用put方法,调用resize()时
if ((tab = table) == null || (n = tab.length) == 0)
// 调用resize()初始化桶数组
n = (tab = resize()).length;
// i:根据key计算的hash值,得到数组下标
// 判断是否发生了hash冲突,即当前位置是否已经存在节点
if ((p = tab[i = (n - 1) & hash]) == null)
// 建立新的节点
// newNode(hash, key, value, null) = new Node<>(hash, key, value, next)
tab[i] = newNode(hash, key, value, null);
else { // 发生了hash冲突
Node<K,V> e; K k;
// 判断新节点的key与旧节点的key和hash值是否相同
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
// 新值替换旧值
e = p;
// 判断新数据是否为红黑树
else if (p instanceof TreeNode)
// 调用树节点putTreeVal插入数据
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
// 第一个元素没有加入到binCount中,所以-1
if (binCount >= TREEIFY_THRESHOLD - 1)
// 数组长度小于64还是只扩容,不树化
treeifyBin(tab, hash);
break;
}
// 在链表中找到相同的key,直接替换value
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// 说明只是遍历到中间就break了,该种情况是在链表中找到了完全相等的key
if (e != null) {
// 保存旧值
V oldValue = e.value;
// 判断是否需要替换
if (!onlyIfAbsent || oldValue == null)
e.value = value;
// 这是一个默认实现为空的函数,用作LinkedHashMap重写使用
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
// 插入成功后,判断实际存在的键值对数量size > 最大容量threshold,若 > ,则进行扩容
if (++size > threshold)
resize();
// 插入成功时会调用的方法(默认实现为空)
afterNodeInsertion(evict);
return null;
}
扩容机制resize()
// resize有两种使用情况,一是进行初始化,二是数组容量不够进行扩容
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table; // 扩容前的数组
int oldCap = (oldTab == null) ? 0 : oldTab.length; // 扩容前数组的容量=长度
int oldThr = threshold; // 扩容前的数组的阈值
int newCap, newThr = 0;
// 扩容前的数组容量超过最大值,不进行扩容
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 无法超过最大值,扩容为原来的两倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1;
}//如果当前表是空的,但是有阈值。代表是初始化时指定了容量、阈值的情况
else if (oldThr > 0)
newCap = oldThr;
else { // 如果当前表是空的,而且也没有阈值。代表是初始化时没有任何容量/阈值参数的情况
// 新数组容量为默认的16
newCap = DEFAULT_INITIAL_CAPACITY;
// 新的阈值=默认的容量16*默认加载因子0.75
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
// 如果新的阈值为0
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"})
// 根据新的阈值构建新的hash桶
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
// 更新hash桶的引用
table = newTab;
// 如果旧hash桶中有元素,将旧的桶中的元素转移到新的桶
if (oldTab != null) {
// 遍历旧hash桶
for (int j = 0; j < oldCap; ++j) {
// 取出当前节点e
Node<K,V> e;
// 如果桶中有元素,则赋值给e
if ((e = oldTab[j]) != null) {
// 将旧hash桶置空,方便GC
oldTab[j] = null;
// 如果当前链表就一个元素
if (e.next == null)
// 将元素放入新hash桶中
// 新桶的下标取值为 hash值与桶的长度-1
newTab[e.hash & (newCap - 1)] = e;
// 如果发生hash碰撞且节点长度超过8,转换为红黑树
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // 如果发生hash碰撞且节点长度小于8,则根据链表上每个节点的hash值放入到新桶对应的下标位置
// 低位链表的头节点和尾节点
Node<K,V> loHead = null, loTail = null;
// 高位链表的头节点和尾节点
Node<K,V> hiHead = null, hiTail = null;
// 临时节点
Node<K,V> next;
do {
next = e.next;
//这里是一个利用位运算 代替常规运算的高效点: 利用哈希值 与 旧的容量,可以得到哈希值去模后,是大于等于oldCap还是小于oldCap,等于0代表小于oldCap,应该存放在低位,否则存放在高位
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);
// 将低位链表放在原index处
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
// 将高位链表放在新index处
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
查询get()
public V get(Object key) {
Node<K,V> e;
// 查询成功返回value,失败返回null
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
// first为要查找的key的前置节点
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
// 数组不为空并且数组长度>0,并且数组的前置节点不为空
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;
}
删除remove()
public V remove(Object key) {
Node<K,V> e;
// 删除成功返回目标key的value值,否则返回null
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;
// p是待删除结点的前置节点
// 判断数组是否为空并且长度>0
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
// node为待删除节点
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
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
// 遍历链表,链表所在节点赋值给node
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
// 从哈希表中删除某个节点, 如果参数matchValue是true,则必须key 、value都相等才删除。
// 如果movable参数是false,在删除节点时,不移动其他节点
// 如果有待删除节点node,且 matchValue为false,或者值也相等
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);
// node节点为首节点(链表节点),将下一个节点置于头节点
else if (node == p)
tab[index] = node.next;
else
// 删除的节点在链表中间
p.next = node.next;
// hashmap修改次数增加
++modCount;
// hashmap长度减小
--size;
// LinkdHashMap回调函数
afterNodeRemoval(node);
return node;
}
}
return null;
}
本人也在一步步的学习中,如发现有不对的地方,欢迎指正。
另本人会在私人公众号不定时推送一些知识文章,欢迎各位订阅哦。