HashMap
简介
HashMap最早出现在JDK1.2中,底层是散列算法实现,Hash是允许null键值对的,在计算Hash的时候为0 ,并且HashMap不是线程安全的类,多线程下可能存在问题。
原理
通过hash的方法,通过put和get存储和获取对象,储存对象的时候,我们将键值对传递给put方法,该方法会调用hashCode方法计算出hash值得到桶的位置进行进一步的存储。hashMap会根据当前桶的占有情况自动调整容量。
源码分析
构造方法
//空参数构造方法,默认将负载因子设置成0.75f 设置成0.75f的好处是它正好的3/4 而桶的数量正好的2的幂次方,这两个数的乘积正好为整数
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
//自定义负载因子,这个地方会有一步判断 为0的时候抛出异常,不能大于最大值,当然这个值很大,我们基本不会到
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
//将一个map放到HashMap,这个不是很常用
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
//设置初始容量,负载因子
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
HashMap常用的参数
名称 | 用途 |
---|---|
initialCapacity | HashMap 初始容量 |
loadFactor | 负载因子 |
threshold | 当前 HashMap 所能容纳键值对数量的最大值,超过这个值,则需扩容 |
/** The default initial capacity - MUST be a power of two. */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; //使用这个就是左移4位相当于1扩大2的4次方倍 这个方法效率更高
/** The load factor used when none specified in constructor. */
static final float DEFAULT_LOAD_FACTOR = 0.75f;
final float loadFactor;
/** The next size value at which to resize (capacity * loadfactor). */
int threshold;
threshold (阈值)
threshold 的值为capacity * loadfactor 但是在HashMap(int initialCapacity, float loadFactor)构造方法中我们发现阈值是根据下面的方法计算的:
/**
* Returns a power of two size for the given target capacity.
*/
static final int tableSizeFor(int cap) {
int n = cap - 1;
//>>>表示无符号右移,也叫逻辑右移,即右移后左边空出的位用零来填充。移出右边的位被丢弃.下面的就是n向右一东西1位并且将右边的一位抛弃
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
这个算法就是根据用户传入的容量值(代码中的cap),通过计算,得到第一个比他大的2的幂并返回。
负载因子(loadFactor)
对于HashMap来说 loadFactor是一个很重要的参数,该参数反应了 HashMap 桶数组的使用情况(假设键值对节点均匀分布在桶数组中)。通过调节负载因子,可使 HashMap 时间和空间复杂度上有不同的表现。当我们调低负载因子时,HashMap 所能容纳的键值对数量变少。扩容时,重新将键值对存储新的桶数组里,键的键之间产生的碰撞会下降,链表长度变短。此时,HashMap 的增删改查等操作的效率将会变高,这里是典型的拿空间换时间。相反,如果增加负载因子(负载因子可以大于1),HashMap 所能容纳的键值对数量变多,空间利用率高,但碰撞率也高。这意味着链表长度变长,效率也随之降低,这种情况是拿时间换空间。至于负载因子怎么调节,这个看使用场景了。一般情况下,我们用默认值就可以了。
get()方法
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
hash()方法
//计算hash ,这儿我们就能看到当key为null的时候hash就是为0
static final int hash(Object key) {
int h;
//这个地方又有个问题,(h = key.hashCode()) ^ (h >>> 16) 是 高16位和低16位做异或运算,目的是散列更均匀,减少哈希碰撞,提升hashmap的运行效率
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
getNode()方法
first = tab[(n - 1) & hash] 是通过(n - 1)& hash 即可计算出桶的数量,HashMap中桶的数量为2的幂,此时(n - 1)& hash 就等价于对length取余。因为相比于位运算取余的效率低一点,所以在JDK迭代过程中对其进行了优化
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab;
Node<K,V> first, e;
int n; K k;
//最外层的判断,其实就是判断HashMap是否为空
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//使用first 确定桶的位置
//对桶的首节点进行判断,如果相等直接返回
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
//如果 first 是 TreeNode 类型,则调用黑红树查找方法
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;
}
下面看一下getNode()中出现的TreeNode()方法
TreeNode()方法
红黑树性质
- 每个结点都是红色的或者是黑色的
- 根结点是黑色的
- 每个叶结点NIL是黑色的,但是通常我们不考虑NIL叶结点。
- 如果一个结点是红色的,它的两个子结点都是黑色的
- 每个结点到其他所有后代叶结点的简单路径上,均包含相同数目的黑色结点,这个属性被称为黑高,记作bh(x)
内部属性
TreeNode<K,V> parent; //父节点
TreeNode<K,V> left; //左儿子
TreeNode<K,V> right;//右儿子
TreeNode<K,V> prev; //下一个节点
boolean red;//是否为红色
root()方法
/**
* 返回包含此节点的树的根。
*/
final TreeNode<K,V> root() {
for (TreeNode<K,V> r = this, p;;) {
if ((p = r.parent) == null)
return r;
r = p; //不断检查parent是否为null,为null的是根结点
}
}
moveRootToFront()方法
该方法的主要目的是确定根节点保存在table 如果没保存到,就将root取出放到数组的对应位置
static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) {
int n;
if (root != null && tab != null && (n = tab.length) > 0) {
//获取桶的位置
int index = (n - 1) & root.hash;
TreeNode<K,V> first = (TreeNode<K,V>)tab[index]; // 取出 桶对应位置的第一个节点
if (root != first) { //判断root是否为第一个节点
//如果root不是第一个节点,将root替换为第一个节点
Node<K,V> rn;
tab[index] = root;//root放到table[index]位置
TreeNode<K,V> rp = root.prev;
//让root的后节点的前节点指向root的前节点
if ((rn = root.next) != null)
((TreeNode<K,V>)rn).prev = rp;
//让root的前节点的后节点指向root的后节点
if (rp != null)
rp.next = rn;
if (first != null)
first.prev = root;
root.next = first;
root.prev = null;
}
///assert后面的表达式为false时会抛出错误
assert checkInvariants(root);
}
}
checkInvariants()方法
从root开始递归检查红黑树的性质,仅在检查root是否落在table上时调用
static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
tb = t.prev, tn = (TreeNode<K,V>)t.next;
if (tb != null && tb.next != t)//t的前一个结点的后续应为t
return false;
if (tn != null && tn.prev != t)//t的后一个结点的前驱应为t
return false;
if (tp != null && t != tp.left && t != tp.right) //t存在父节点,但是,父节点的左儿子和右儿子有一个应该是t
return false;
if (tl != null && (tl.parent != t || tl.hash > t.hash)) //t的左儿子是tl那么 tl的父节点应该为t 并且tl的hash应该小于t
return false;
if (tr != null && (tr.parent != t || tr.hash < t.hash))//tr的父节点应该为t 并且tr的hash应该大于t
return false;
if (t.red && tl != null && tl.red && tr != null && tr.red) //如果t是红的那么子节点都不能是红色的
return false;
if (tl != null && !checkInvariants(tl))// 递归判断子节点
return false;
if (tr != null && !checkInvariants(tr))
return false;
return true;
}
getTreeNode()(常用)
getTreeNode这个方法在HashMap中被多次使用,左右是寻找某个结点所在的树中是否有hash和key值符合的结点。我们可以看到这个方法一定会确保最后调用的是root.find(),也就是说find方法调用时this一定是根结点。所以无论最初调用getTreeNode的结点在树中处于什么位置,最后都会从根结点开始寻找,由于红黑树是相对平衡的二叉搜索树,所以可以认为搜索时间相比于链表从O(n)下降到了O(lgn)
final TreeNode<K,V> getTreeNode(int h, Object k) {
return ((parent != null) ? root() : this).find(h, k, null);
}
//从根结点寻找h和k符合的结点
//从根结点p开始根据hash和key值寻找指定的结点。kc是key的class
final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
TreeNode<K,V> p = this;//该方法调用时this是根结点
do {
int ph, dir;
K pk;
TreeNode<K,V> pl = p.left, pr = p.right, q;
if ((ph = p.hash) > h)//p.hash>参数hash时,移向左子树
p = pl;
else if (ph < h)//p.hash<参数hash时,移向右子树
p = pr;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;//p.hash=参数hash,且p.key与参数key相等找到指定结点并返回
else if (pl == null) //若hash相等但key不等,向左右子树非空的一侧移动
p = pr;
else if (pr == null)
p = pl;
else if ((kc != null ||
(kc = comparableClassFor(k)) != null) &&
(dir = compareComparables(kc, k, pk)) != 0)
p = (dir < 0) ? pl : pr;
else if ((q = pr.find(h, k, kc)) != null)
return q;
else
p = pl;
} while (p != null);
return null;
}
keySet()方法
keySet方法主要用于遍历map使用的
public Set<K> keySet() {
Set<K> ks = keySet;
if (ks == null) {
ks = new KeySet();
keySet = ks;
}
return ks;
}
final class KeySet extends AbstractSet<K> {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
public final Iterator<K> iterator() { return new KeyIterator(); }
public final boolean contains(Object o) { return containsKey(o); }
...
}
这儿主要看KeyIterator()方法的父类HashIterator
abstract class HashIterator {
Node<K,V> next; // next entry to return
Node<K,V> current; // current entry
int expectedModCount; // for fast-fail
int index; // current slot
HashIterator() {
expectedModCount = modCount;
Node<K,V>[] t = table;
current = next = null;
index = 0;
//寻找包含节点的桶
if (t != null && size > 0) { // advance to first entry
do {} while (index < t.length && (next = t[index++]) == null);
}
}
public final boolean hasNext() {
return next != null;
}
final Node<K,V> nextNode() {
Node<K,V>[] t;
Node<K,V> e = next;
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
if (e == null)
throw new NoSuchElementException();
//寻找下一个包含链表节点引用的桶
if ((next = (current = e).next) == null && (t = table) != null) {
do {} while (index < t.length && (next = t[index++]) == null);
}
return e;
}
...
}
遍历的全过程为:
- 获取键集合KeySet对象
- 通过KeySet的迭代器KeyIterator进行遍历,因为其继承至HashIterator ,主要的逻辑存在于HashIterator
- HashIterator 先去寻找包含链表节点引用的桶 ,然后对桶中的链表进行遍历,遍历结束,再去寻找其他的桶循环
put方法
put方法主要的逻辑还是调用了putVal方法,代码如下:调用方式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,table 被延迟到插入新数据时再进行初始化
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//使用hash 与数组长度-1 进行异或运算,从而得到数组的下标,并判断该节点是否为空,如果为空就直接创建新的键值对节点,其中长度为n的一个二次幂
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
//如果key索引的数组位置不为空,就会出现碰撞
Node<K,V> e; K k;
//首先判断
//比较hash 和key 在不为空的情况下相等说明,两个key是一样的,则当前节点使用e储存
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//然后 判断该节点也就是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);
//从0开始 如果到节点储存的为8 就需要转换为红黑树了
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//找到碰撞节点后,key完全相同的节点,使用新节点替换老节点
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// 此时的e是保存的被碰撞的那个节点,即老节点
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
// onlyIfAbsent是方法的调用参数,表示是否替换已存在的值,
56 // 在默认的put方法中这个值是false,所以这里会用新值替换旧值
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
// map变更性操作计数器
// 比如map结构化的变更像内容增减或者rehash,这将直接导致外部map的并发
// 迭代引起fail-fast问题,该值就是比较的基础
++modCount;
// size即map中包括k-v数量的多少
// 当map中的内容大小已经触及到扩容阈值时,则需要扩容了
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
putTreeVal()方法
该方法是当table下的结构为红黑树的时候,新增的时候的添加操作
final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
int h, K k, V v) {
Class<?> kc = null;
boolean searched = false;
TreeNode<K,V> root = (parent != null) ? root() : this;// 找到root根节点
for (TreeNode<K,V> p = root;;) { //从根节点开始遍历
int dir, ph; K pk;
//通过hash值判断放的位置
if ((ph = p.hash) > h)
//大于放在右侧
dir = -1;
else if (ph < h)
//小于放在左侧
dir = 1;
// 如果key 相等 直接返回该节点的引用 外边的方法会对其value进行设置
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
/**
*下面的步骤主要就是当发生冲突 也就是hash相等的时候
* 检验是否有hash相同 并且equals相同的节点。
* 也就是检验该键是否存在与该树上
*/
//说明进入下面这个判断的条件是 hash相同 但是equal不同
// 没有实现Comparable<C>接口或者 实现该接口 并且 k与pk Comparable比较结果相同
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0) {
//在左右子树递归的寻找 是否有key的hash相同 并且equals相同的节点
if (!searched) {
TreeNode<K,V> q, ch;
searched = true;
if (((ch = p.left) != null &&
(q = ch.find(h, k, kc)) != null) ||
((ch = p.right) != null &&
(q = ch.find(h, k, kc)) != null))
return q;
}
//说明红黑树中没有与之equals相等的 那就必须进行插入操作
//打破平衡的方法的 分出大小 结果 只有-1 1
dir = tieBreakOrder(k, pk);
}
//下列操作进行插入节点
//xp 保存当前节点
TreeNode<K,V> xp = p;
//找到要插入节点的位置
if ((p = (dir <= 0) ? p.left : p.right) == null) {
Node<K,V> xpn = xp.next;
//创建出一个新的节点
TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
if (dir <= 0)
//小于父亲节点 新节点放左孩子位置
xp.left = x;
else
//大于父亲节点 放右孩子位置
xp.right = x;
//维护双链表关系
xp.next = x;
x.parent = x.prev = xp;
if (xpn != null)
((TreeNode<K,V>)xpn).prev = x;
//将root移到table数组的i 位置的第一个节点
//插入操作过红黑树之后 重新调整平衡。
moveRootToFront(tab, balanceInsertion(root, x));
return null;
}
}
}
添加树形节点,与添加双链表节点个过程类似:
1、从root节点开始寻找 如果目标k.hash 小于 当前节点的 hash ,那么到左树寻找,大于那么从右树寻找。如果找到key相同并且equals相同的节点 p 那就直接返回。
2、如果hash相同 但是equal不同 进而通过Comparable接口,进行比较,如果比较的结果如果还是相等,则在左右子树递归的寻找是否有与要插入的key equals相同的元素。如果有那么直接return返回。
(也即是没实现Comparable接口,大小由hash判定。实现了,则由Comparable接口的比较方法判定)
3、如果遍历完所有的节点 并未找到equals相同的节点。那就需要插入该新节点。必须分出大小,所以通过执行tieBreakOrder方法,该方法的返回值是-1,1。如果是-1则插入到左边节点,1就插入到右边节点。
4、插入完成之后,需要重新移动root节点 到table数组的i位置的第一个节点上 并且需重新平衡红黑树
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;
}
待完善。。。。。