HashMap原理讲解
1.HashMap的继承体系图
这张图上最重要的接口是Map接口,AbstractMap是Map的抽象实现,HashMap接口又继承了AbstractMap,HashMap对AbstractMap已经重写得差不多了
2.Node数据结构
//Node源码
static class Node<K,V> implements Map.Entry<K,V> {
final int hash; //数据存入的地方,是K的hash值经过扰动得到的值
final K key; //键
V value; //值
Node<K,V> next; //碰撞之后形成链表,用于指向下一个元素
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
3.底层存储结构图
如果没有冲突,Node元素就会被放在数组中,如果产生冲突,就会形成链表,如果链表长度大于8,同时整个哈希表里的元素超过64个时,该链表转化为红黑树
4.put数据原理图
5.什么是Hash碰撞?
如果两个输入串的hash函数的值一样,则称这两个串是一个碰撞
6.什么是链化?
碰撞后由于hash相同,所以存储在数组上的同一个位置,形成链表结构
7.jdk8为什么引入红黑树?
为了解决链化后由于链表过长而查找复杂
8.HashMap扩容原理?
以空间换时间,增大数组长度,减少了链表长度
下图可以帮助理解,数组从16个元素扩容到32个元素,具体为什么元素要分配到这个地方需要用hash值进行计算,这里不展开