HashMap
HashMap可以说60%都会被问到,底层是数组+链表的结构。在Jdk8引入了红黑树对链表进行优化提升了检索效率,既然这个玩意儿出现的频率十分高,并且在日常工作中使用可谓相当之频繁,并且redis的数据结构其实和HashMap是类似的,后面讲Redis会讲到。既然用处这么大,那我觉得有必要着重细化来讲HashMap这个数据结构。
HashMap结构

从上面的图可以看到左边部分是连续的数据结构,其实他是有数据来实现的。右边是从数组所在位置开始有上个节点指向下个节点的结构,大家很容易就联想到了是单向链表结构。到了这里就从大体上理解了HashMap的结构了,在Jdk8中还引入了红黑树。
HashMap一些概念
既然HashMap是数组+链表的结构,那刚刚new的时候一些初始值是多少呢?
数组的默认长度是16,随着放入值的数量越多,默认16个桶肯定是放不下的,那么就会产生扩容。数组的扩容机制是当数组的存放值的数量超过数组长度的3/4时数组就会扩容(这个3/4=0.75,就是负载因子),长度会扩容两倍。
源码解读-get
既然上面提到了Map是KV键值对,那么get和put就时重点API了
/**
* java8 get操作
* hash:hashCode
**/
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其实是数组的桶位置,如果根据hash定位的数组都是null,就链表一定为空
(first = tab[(n - 1) & hash]) != null) {
// 如果数组的hash相等并且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;
}
源码解读-put
/**
* java8 put操作
* hash:hashCode
**/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
// 初始化数组
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
// 如果根据hashCode定位的数组桶值为空,那就把value进行包装成Node,然后存放在此桶上
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
// 如果数组上的Node的hash和key都相等,那就将存放在此桶上
e = 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个,那么会转为红黑树,其实还有个条件数组长度要大于等于64
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))))
// 遍历到链表元素的key和hash都相等的情况就停止遍历,将将值存放在链表此位置
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;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}