HashMap
一,字段方法介绍
1.常量字段介绍
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 2的四次方,初始化默认的容量
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; //桶中的数据采用红黑树存储时,整个table的最小容量
字段:
transient Node<K,V>[] table; //存储主干,节点数组
transient Set<Map.Entry<K,V>> entrySet;
transient int size; //元素数量
transient int modCount; //修改次数
//The next size value at which to resize (capacity * load factor).
int threshold; //下一次扩容的大小,
final float loadFactor; //负载因子
node节点结构:
static class Node<K,V> implements Map.Entry<K,V> {
final int hash; //节点的hash值
final K key; //存入的key值
V value; //存放的值
Node<K,V> next; //下一个节点
....
}
TreeNode节点结构: 注意红黑树节点中,并没有key和value值,只有指针和颜色。因为node是它的父类的父类,所以key和value保存到父类之中。
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
TreeNode<K,V> parent; // red-black tree links
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev; // needed to unlink next upon deletion
boolean red;
2.构造函数
2.1常用的无参构造:
默认构造方法,就直接给负载因子赋值,其他没有操作,其他字段都是默认的。
// Constructs an empty <tt>HashMap</tt> with the default initial
// capacity (16) and the default load factor (0.75).
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
2.2带初始化容器大小,和负载因子的构造方法:
首先要判断传入参数的正确性,然后赋值。
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
2.3带集合的构造方法:
传入一个Map集合,调用put方法进行初始化。
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
从上面的代码中可以看到,在构造方法中并没有初始化table,具体的table初始化是在put操作上进行的。
3.添加
put()是一个入口方法,实际调用的是putVal()方法,其中通过hash()方法计算了key对应的 值
public V put(K key, V value) {
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);
}
具体的putVal()方法,内容很长
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i; //变量初始化,n表示table的长度
if ((tab = table) == null || (n = tab.length) == 0) //容器初始化
n = (tab = resize()).length; //通过resize()方法获取分配空间。
if ((p = tab[i = (n - 1) & hash]) == null) //如果新的位置是空的,则直接放入,否者要解决冲突
tab[i] = newNode(hash, key, value, null); //将value封装成新的node
else { //解决冲突
Node<K,V> e; K k;
// 注意p的赋值在 第二个if里面,它表示的是冲突位置所存放的节点。
//如果新传入的节点和当前node的hash和key相同,则下面再处理
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
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);
if (binCount >= TREEIFY_THRESHOLD - 1) // 链表元素数量>=8,链表转红黑树
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//更新当前传入的值到当前node中。返回之前的oldValue
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount; //修改次数+1,
if (++size > threshold) //空间大小,如果超过了阈值,要扩容
resize();
afterNodeInsertion(evict);
return null;
}
其中涉及的重点方法:resize()方法,返回新分配的空间。
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;//获取老的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 { // 第一次初始化 oldCap=0,oldThr=0
newCap = DEFAULT_INITIAL_CAPACITY; //默认大小,16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); //默认计算方法,16*0.75,12
}
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;
}
4.get()操作
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value; //代码内容在这里
}
调用getNode()方法,计算hash(key)值,通过Hash来获得node
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) {
//第一个 检测数组中的hash定位获得第一个Node
if (first.hash == hash &&((k = first.key) == key || (key != null && key.equals(k))))
return first;
//第一个不是,那么就是后续节点中,可能是链表形式,可能是红黑树
if ((e = first.next) != null) {
if (first instanceof TreeNode) //如果是红黑树,通过getTreeNode()方法获得
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;
}
链表形式的获取比较简单,红黑树的获得,我们放在下面红黑树单独进行介绍。
5.链表转红黑树
java8为了降低冲突链表中,遍历查询慢的问题,将链表元素超过8个之后,将链表转为红黑树结构,如此访问速度加快。
注意当节点数量达到8之后,不会直接进行链表转换,而是先判断是否需要扩容。
min_treeify_capacity: 64默认值
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) { //获得table中的节点
TreeNode<K,V> hd = null, tl = null;
do { //链表遍历
TreeNode<K,V> p = replacementTreeNode(e, null); //将node节点,转成treeNode节点
if (tl == null)
hd = p; //存放根节点
else { //前置节点t1,串通
p.prev = tl;
tl.next = p;
}
tl = p; //保存前置节点。
} while ((e = e.next) != null);
//上面的操作,只是把node节点,转成TreeNode节点,连接起来,还没有形成二叉树的形态
if ((tab[index] = hd) != null)
hd.treeify(tab); //二叉化
}
}
treeify()二叉结构 构造:
final void treeify(Node<K,V>[] tab) {
TreeNode<K,V> root = null;
//遍历
for (TreeNode<K,V> x = this, next; x != null; x = next) {
next = (TreeNode<K,V>)x.next;
x.left = x.right = null;
if (root == null) { //根节点
x.parent = null;
x.red = false;
root = x;
}
else {
K k = x.key;
int h = x.hash;
Class<?> kc = null;
//死循环 双层遍历(第一层遍历 链表,第二层遍历 红黑树)
for (TreeNode<K,V> p = root;;) {
int dir, ph; //保存节点的值。
K pk = p.key;
if ((ph = p.hash) > h) //x节点应属左边
dir = -1;
else if (ph < h) //x节点,应属右边
dir = 1;
else if ((kc == null && //hash值相等
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0)
dir = tieBreakOrder(k, pk);
TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) { //进入子节点,如果为空,则直接赋值
x.parent = xp; //赋值,插入新节点。
if (dir <= 0)
xp.left = x;
else
xp.right = x;
root = balanceInsertion(root, x); //平衡。
break;
}
}
}
}
moveRootToFront(tab, root);
}
一个节点,一个节点的插入,插入的过程和普通的平衡二叉树 插入过程相同,红黑树不同点之处,在于插入之后,会有一个平衡的过程,在该过程中涉及到了节点的旋转。旋转的具体过程,在我的数据结构---红黑树中有介绍。
红黑树的操作:https://blog.csdn.net/W1427259949/article/details/107653444
总结:
图片转自:https://blog.csdn.net/woshimaxiao1/article/details/83661464
二,系数分析
1.为什么不直接使用红黑树?
答:红黑树节点占用空间是node的2倍,在节点少的情况下,红黑树占用大空间的劣势>时间复杂度上的优势,只有当节点数量比较多的时候,才会返回,优势大于劣势。
2. 为什么节点数达到8才转红黑树?
答:链表中的节点数量遵循泊松分布,当节点数量达到8的概率很低,而且这个时候检索效率也很低,所以在小概率和低效率的极端环境下,才将链表转为红黑树。而且转换的过程中是需要消耗的。而且链表会不断的进行是否扩容的检查,扩容之后,链表的长度会平均下降。
注意:
hashMap并不是在链表元素个数大于8就一定会转换为红黑树,而是先考虑扩容,扩容达到默认限制后才转换。
hashMap的红黑树不一定小于6的时候才会转换为链表,而是只有在resize的时候才会根据 UNTREEIFY_THRESHOLD 进行转换。
参考链接:
1.https://www.jianshu.com/p/d4fee00fe2f8(jdk 1,8)
2.https://blog.csdn.net/woshimaxiao1/article/details/83661464(jdk 1.7)
3.https://blog.csdn.net/baidu_37147070/article/details/98785367(系数分析)