HashMap实际上是一个元素为链表的数组。当添加一个元素时,先计算元素key的hash值,用来确定插入数组中的位置,也存在hash值会相等的情况,则会插入到同一位置,形成链表结构,当链表长度达到一定长度时,链表会转换成红黑树,这样会减少查询时间。其数据结构简单归纳为数组(位桶)+链表+红黑树。
(1)数据结构更佳:JDK1.6、1.7采用位桶+链表,用链表解决碰撞冲突,当存在Hash值相同时,只采取链表储存数据;JDK1.8采用位桶数组+链表+红黑树实现,当链表长度超过阀值(8)时,将链表转换成红黑树。
(2)效率更高:JDK1.6、1.7中,单纯链表查询的时间复杂度为O(n);JDK1.8中,当链表转换为红黑树时,查询的时间复杂度为O(logn)。
(1)数组元素Node
static class Node implements Map.Entry {
final int hash;
final K key;
V value;
Node next;
Node(int hash, K key, V value, Node next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry,?> e = (Map.Entry,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
(2)红黑树
static final class TreeNode extends LinkedHashMap.Entry {
TreeNode parent; // 父节点
TreeNode left; // 左子树
TreeNode right; // 右子树
TreeNode prev;
boolean red; //颜色属性(红黑色)
TreeNode(int hash, K key, V val, Node next) {
super(hash, key, val, next);
}
/**
* 返回当前节点的根节点
*/
final TreeNode root() {
for (TreeNode r = this, p;;) {
if ((p = r.parent) == null)
return r;
r = p;
}
}
HashMap本身是以时间换空间,所以加权因子不必很大,但也不能太小,否则会导致浪费空间。当数组中的元素为链表,且长度大于等于8,链表会转换为红黑树;当数组中的元素为红黑树,且长度为小于等于6,红黑树会转换为链表。
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 默认初始化容量
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; // 最小转换容量
构造函数有四种方式,最后一种为构造时就给对象添加健值对。
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); //新的扩容阀值
}
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR); //加权因子为默认值
}
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; //只设置加权因子为默认值
}
public HashMap(Map extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
final void putMapEntries(Map extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
if (table == null) { // pre-size
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
threshold = tableSizeFor(t);
}
//当m的size大于新的扩容阀值,需重新扩容
else if (s > threshold)
resize();
for (Map.Entry extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
//添加健值对
putVal(hash(key), key, value, false, evict);
}
}
}
(1)存机制:put(key, value)
简述添加健值对过程:a.判断健值对数组tab[]是否为空,否则进行扩容。b.根据健值key计算hash值得到插入数组的索引,如果该索引位置值为空,直接新建节点添加。c.判断当前处理hash冲突的是链表还是红黑树,然后分别进行处理。
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node[] tab; Node p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
//新建节点把值插入到该位置
tab[i] = newNode(hash, key, value, null);
//表示存储有冲突:首先通过链表处理,当链表长度为8时转换成红黑树
else {
Node e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode)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个,看是否需要改变冲突节点的存储结 构,
//treeifyBin首先判断当前hashMap的长度,如果不足64,只进行扩容,如果达到64,那么将冲突的存储结构为红黑树
if (binCount >= TREEIFY_THRESHOLD - 1)
treeifyBin(tab, hash);
break;
}
//如果有相同的值就结束遍历
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
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;
//如果当前大小大于门限,门限原本是初始容量*0.75
if (++size > threshold)
resize(); //再次扩容
afterNodeInsertion(evict);
return null;
}
(2)取机制:get(Object key)
简述取值过程:a.计算链表数组中的第一个Node。b.判断第一个Node的key值与参数的key值是否相等,不相等就遍历链表找到相等的key值返回对应的value。
public V get(Object key) {
Node e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node getNode(int hash, Object key) {
Node[] tab; Node first, e; int n; K k;
//找到第一个插入的Node
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//判断条件为hash值和key值都需要相同
if (first.hash == hash &&
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode)first).getTreeNode(hash, key);
//遍历first后面的链表,找到key值和hash值都相同的Node
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
在构造hash表时,如果不指明初始大小,默认大小为16,如果Node[]数组中的元素达到重新调整的HashMap的大小,则需要扩容为原来的两部,扩容很好耗时。
final Node[] resize() {
Node[] 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[] newTab = (Node[])new Node[newCap];
table = newTab;
if (oldTab != null) {
//遍历原来的旧表
for (int j = 0; j < oldCap; ++j) {
Node 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)e).split(this, newTab, j, oldCap);
//如果e后边有链表,到这里表示e后面带着个单链表,需要遍历单链表,将每个结点重
else { // preserve order
Node loHead = null, loTail = null;
Node hiHead = null, hiTail = null;
Node next;
do {
next = e.next;
//新表是旧表的两倍容量,实例上就把单链表拆分为两队,
//e.hash&oldCap为偶数一队,e.hash&oldCap为奇数一对
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) { //lo队不为null,放在新表原位置
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) { //hi队不为null,放在新表j+oldCap位置
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}