1、hash表
- hash表也称散列表(Hash Table),是根据键值(Key Value)而进行直接访问的数据结构。通过把键Key映射到表的某一位置来访问,以加快查询速度。Key值和存储它的位置存在唯一一个确定关系函数f(x),成为hash函数(散列函数)。
2、hashcode
- hashcode通过hash函数计算得到,且在hash表中有对应的位置。
- 每个对象都有hashcode,通过将对象的物理地址转化为一个整数,将整数通过hash计算就可以得到hashcode。
- hashCode方法可重写。如String类的hashCode方法,保证了内容相同的字符hashcode相等,但是hashcode一样时字符串内容不一定相同。
3、HashMap的hash()函数
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
- 先获取key的hashCode,在把该hashcode进行右移16位并与原hashcode做异或。高位与低位的异或操作,可以混合高低位的特征信息,增加hashcode的随机性,减少hash冲突的概率。
4、size和index的计算
- HashMap底层的哈希表的大小总是2的倍数,通过如下函数进行计算。
/* 这个方法是基于给定的 size 计算一个不小于 size 的 2^n,实际上相当于把 cap - 1 的
最高位及其后面所有的低位都置为 1,得到 2^n - 1,最后结果 +1 得到 tableSize. */
static final int tableSizeFor(int cap) {
int n = cap - 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为7,那么计算步骤如下:
6 = 7 - 1;
6 = 0110;
0110
| 0011
-------------
0111
//以此类推,得到size = 8。
- HashMap底层的哈希表大小为2的倍数,可在计算key值的index上有所优化。当底层数组的 length 为 2^n 时, h & (length - 1) 就相当于对 length 取模,其效率要比直接取模高得多。
5、HashMap主要方法
- V get(Object key)
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
通过调用getNode(int hash, Object key)方法获取数据
// table为哈希表
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
// 判断哈希表示会否为空,若不为空则通过hash值对哈希表的大小进行取模得到该hash值所在节点的下标,否则返回null。
if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) {
//如果该下标的第一个Node节点的key值和hash值与上送参数一致,则返回该节点,否则出现hash冲突。
if (first.hash == hash && ((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
// 若first节点为红黑树,则进行红黑树处理
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;
}
- V put(K key, V value)
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
通过调用putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict)方法存储数据
// onlyIfAbsent表示在已有key/value的情况下,是否用新的value替换旧的value
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)
// 当原map大小为0时,将哈希表大小左移1位,即大小置位1,相当于初始化。
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
// 当该下标没有值,则直接new个node放置在该位置
tab[i] = newNode(hash, key, value, null);
else {
// 否则要解决hash冲突
Node<K,V> e; K k;
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
// 如果key值相同,不再额外遍历或树处理
e = p;
else if (p instanceof TreeNode)
//jdk8以后,链表长度超过8会将链表转换为红黑树进行处理。表示冲突较多。
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
// 链表处理
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
//如果子节点为null,则实例化一个Node,赋予子节点。
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
// TREEIFY_THRESHOLD 为8,即转换为红黑树的阈值
treeifyBin(tab, hash);
break;
}
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
// 发现相同key值,跳出循环
break;
p = e;
}
}
// 此时e指向的即key和hash值相同的Node节点
if (e != null) {
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
// 如果onlyIfAbsent 为false或者旧值为null,则设置新值
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
// modifyCount,修改次数+1
++modCount;
if (++size > threshold)
// 阈值一般为2^n*0.75,超过则resize()
resize();
// HashMap未用到,LinkedHashMap用
afterNodeInsertion(evict);
return null;
}
- V putIfAbsent(K key, V value)
public V putIfAbsent(K key, V value) {
return putVal(hash(key), key, value, true, true);
}
跟put()方法无差,onlyIfAbsent这个参数传true。
- Node<K,V>[] resize()
大致上来说,是将length左移1位,使容量扩大为原来的2倍。同时会重新导致部分节点位置变化至高1位的位置。
resize()方法有开销的,所以尽量在hashmap初始化的时候,指定大小,须注意阈值。如需存储大小为1000的键值对,2^10为1024,但是阈值比例为0.75,即容量阈值为1024 * 0.75 = 768,所以初始化Map大小设置为2048较为合适。