HashMap
概述
基于哈希表的Map接口的非同步实现。提供所有的映射操作,允许null值和null键。不保证映射的顺序,不保证顺序恒久不表。
数据结构
链表散列:数组+链表
transient Entry[] table;
static class Entry<K, V> implements Map.Entry<K, V> {
final K key;
V value;
Entry<K, V> next;
final int hash;
......
}
存取
存储
当往HashMap中put元素时,先根据key的hashCode重新计算hash值,根据hash值得到这个元素在数组中的位置(即下标),如果数组该位置上已有其他元素,那么在这个位置上的元素以链表的形式存放,新加入的放在链头,最早加入的放在链尾。如果该位置没有元素,则直接将元素放到该位置。
public V put(K key, V value) {
if(key == null)
return putForNullKey(value);
int hash = hash(k.hashCode());
int i = indexFor(hash, table.length);
//遍历Entry以寻找是否已有元素的key与新加入的key相同
for(Entry<K, V> e = table[i]; e != null; e=e.next) {
Object k;
//相同则覆盖
if(e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
//不同则将新添加的Entry与原有Entry形成Entry链,新添加的为头部
addEntry(hash, key, value, i);
return null;
}
static int hash(int h) {
h ^=(h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
对于任意给定对象,只要hashCode()返回值相同,则调用hash(int h)方法计算得到的hash码总是相同的。将hash值对数组长度取模运算,使元素尽量平均。但取模运算消耗较大,因此采用如下的方法indexFor()来计算对象的索引。
static int indexFor(int h, int length) {
return h & (length - 1);
}
由于HashMap的初始化中容量始终为2的幂,此时h & (length - 1)等价于h % length,并且更有效率。
读取
public V get(Object key) {
if(key == null)
return getForNullKey();
int hash = hash(key.hashCode());
for(Entry<K, V> e = table[indexFor(hash,table.length)]; e != null; e = e.next) {
Object k;
if(e.hash == hash && ((k = e.key) == key) || key.equals(k)))
return e.value;
}
return null;
}
总体来讲,Hash Map在底层将key-value当作整体处理,即一个entry对象。用一个Entry[]数组来存储所有的键值对,当需要存储一个Entry对象时,根据hash算法来决定其存储位置,在根据equals方法决定其数组位置上的链表的存储位置。当查询时,同样根据hash找到存储位置,根据equals找到链表上所在的位置。
resize
非常耗时的操作,当元素越来越多时,hash冲突的几率也就越高,查询效率降低。解决方法即为resize,进行扩容。每次扩容则需重新计算位置,并放进去。因此在已知容量的情况下,应预设容量。
threshold = (int)(capacity * loadFactor); //容量 * 负载因子,缺省容量值为16
if(size++ >= threshold)
resize(2 * table.length);
Fail-Fast机制
HashMap线程不安全,如果在使用迭代器的过程中有其他线程更改了map,则抛出concurrentModificationException,此即Fail-Fast策略。通过modCount域来实现,记录修改次数,迭代器初始化时将值传给迭代器的expectedModCount。
https://www.iteye.com/blog/zhangshixi-672697
String等类型如何转化为key
每种类型的hashCode方法不同,对于String类型:
public int hashCode() {
int h = hash;
//value为字符串转的char数组
if(h == 0 && value.length > 0) {
char val[] = value;
for(int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
hashCode()方法的作用,为什么有时需要重写
如上,每种类型都有自己的hasCode()方法,在HashMap中方便使用。