# HashMap解析

## 基本概念

Map集合即Key-Value的集合，前面加个Hash，即散列，无序的。所以HashMap即散着的,无序的Key-Value集合.我们来看看Map的Node的结构

static class Node<K,V> implements Map.Entry<K,V> {
final int hash;//用来做索引，待会会主要介绍这个变量
final K key;//map对应的key
V value;//map对应的value
Node<K,V> next; //map的下一个节点

HashMap的基本数据结构是数组加链表的。就是这种结构

## 初始化

/**
* Constructs an empty {@code HashMap} with the specified initial
*
* @param  initialCapacity 初始化容量
* @throws IllegalArgumentException 初始化容量或者负载因子为负数的时候，抛出参数异常
*/
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
throw new IllegalArgumentException("Illegal load factor: " +
this.threshold = tableSizeFor(initialCapacity);
}

/**
* Returns a power of two size for the given target capacity.
*/
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;
}

### put操作

/**
* 计算key的hash值
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

/**
* 插入key-value
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}

/**
* 实现put操作
*
* @param key的hash值
* @param key值
* @param value值
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return 之前的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;
//1. 如果当前table为空，新建默认大小的table
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//2. 获取当前key对应的节点
if ((p = tab[i = (n - 1) & hash]) == null)
//3. 如果不存在，新建节点
tab[i] = newNode(hash, key, value, null);
else {
//4. 存在节点
Node<K,V> e; K k;
//5. key的hash相同，key的引用相同或者key equals，则覆盖
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//6. 如果当前节点是一个红黑树树节点，则添加树节点
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//7. 不是红黑树节点，也不是相同节点，则表示为链表结构
else {
for (int binCount = 0; ; ++binCount) {
//8. 找到最后那个节点
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//9. 如果链表长度超过8转成红黑树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//10.如果链表中有相同的节点，则覆盖
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;
//是否替换掉value值
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
//记录修改次数
++modCount;
//是否超过容量，超过需要扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}

1. 计算出key的hashCode，记为h
2. h与h右移16位进行异或运算，记为hash
3. hash与当前tab的length-1 进行与运算。得出下标

hashmap获取index的运算过程图：

### Resize扩容机制

...
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
...
if (++size > threshold)
resize();
...

/**
* 初始化table的size或者将table的size翻倍。
* @return the table
*/
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) {
//当前长度超过hashMap定义的最大容量，瓶颈设置为Int的最大值
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//当前长度翻倍后，小于hashMap定义的最大容量并且大于默认初始化容量
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1;//容量翻倍
}
//初始化的时候给了默认容量
else if (oldThr > 0)
newCap = oldThr;
//设置默认大小，初始化HashMap即走空构造的时候
else {
newCap = 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)
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
//还在当前下标的链表
if (loTail != null) {
loTail.next = null;//释放
}
//加上之前容量的下标的链表
if (hiTail != null) {
hiTail.next = null;//释放
}
}
}
}
}
return newTab;
}

n-1: n表示当前tab的长度 ，key1(hash1): 表示key1的hash值，key2(hash2): 表示key2的hash值