HashMap
简介
基于哈希表的 Map 接口的实现
HashMap具有以下特点:
基于数组实现,数组里的元素是一个单向链表。
键不可以重复,值可以重复,键、值都可以为null
非线程安全
HashMap实现了以下接口:
Map:以键值对的形式存取元素
Cloneable:可以被克隆
Serializable:可以序列化
最坏的情况下,链表的查找的时间复杂度为O(n),而红黑树一直则是O(logn),这样会提高HashMap的效率。Jdk7中采用位桶+链表的方式,即散列链表的方式,jdk8中采用的是位桶+链表/红黑树的方式,也是非线程安全的,当某个位桶的链表的长度达到某个阀值时,这个时候链表就会转换成红黑树。当冲突节点数大于8时,转换成红黑树。
HashMap的Node
Node 是HashMap的一个内部类,实现了Map.Entry接口。本质就是一个映射(键值对)
Node[] table 哈希桶数组的初始化长度length默认是16
static class Node<K,V> implements Map.Entry<K,V> {
final int 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;
}
}
Hashmap的put方法实现
- 根据key计算hash值,并根据hash值和数组容量,计算找到索引值index,该位置即为存储该元素的链表所在处。
- 如果没有碰撞直接放在哈希桶中
- 如果碰撞了,以链表的形势存在buckets后
- 如果碰撞导致链表过长(大于等于TREEIFY_THRESHOLD默认值为8),就把链表转换成红黑树
- 遍历table[i]位置的链表,查找相同的key,若找到则则用新的value替换掉oldValue(保证key的唯一性),若没有查找到相同的key,则添加key到table[i]位置,新添加的元素总是添加在单向链表的表头位置,后面的元素称为它的后继。
- 如果超过了最大容量就要进行扩容
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//判断table是否为空
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;//创建一个新的table数组,并且获取该数组的长度
//根据键值key计算hash值得到插入数组的索引i,如果tab[i]==null直接新建节点添加数据
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {//对应节点存在
Node<K,V> e; K k;
//判断table[i]的首个元素是否和key一样,如果相同则直接覆盖value
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)//判断是否为treeNode,即table[i]是否是//红黑树,如果是则直接在数中插入键值对
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//遍历table[i],判断链表长度是否大于TREEIFY_THRESHOLD,大于的话把链表转为红黑树
//在红黑树中执行插入操作,否则进行链表的插入操作。遍历过程中若发现key已经存在//则直接覆盖value即可
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;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
//插入成功后判断实际存在的键值对数量size是否超过了最大容量threshold,如果超过则扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
Hashmap的get方法
- 校验bucket里的第一个结点node tab[(n - 1) & hash],如果直接命中直接返回
- 未命中若为树 ,在树中获取,O(logn)
未命中若为链表 ,在链表中获取,O(n),计算哈希值,根据哈希值与数组容量计算它所在的索引,根据索引查找它所在的链表。在单向链表中查找该元素
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;
}
hashmap的扩容
扩容(resize)就是重新计算容量,向hashmap对象里不停的添加元素,而hashmap对象内部的的数组无法装载更多的元素时,对象就需要扩大数组的长度,以便能装入更多的元素,java里面数组是无法自动扩容的,方法是用一个新的数组替代容量小的数组。使用的是2次幂的扩展(指长度扩展为原来的2倍),所有元素的位置要么是在原来的位置,要么是在原来位置再移动2次幂的位置(原位置+oldCap)
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; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
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 = newTab;
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)
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;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}