static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;// 初始容量16
static final int MAXIMUM_CAPACITY = 1 << 30;// 最大容量2^30
static final float DEFAULT_LOAD_FACTOR = 0.75f;
static final Entry<?,?>[] EMPTY_TABLE = {};
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;// 数组+链表形式存储
transient int size;// 元素数量
int threshold;// 临界值,超过临界值就会扩容 threshold=capacity*loadFactor
// 加载因子,表示hash表中的填满程度, loadFactor ∈ [0, 1]
// loadFactor大时:数组的空间利用率增高,但增加了hash碰撞的概率
// loadFactor小时:数组的空间利用率降低,但降低了hash碰撞的概率
final float loadFactor;
- HashMap的数组是存储在Entry<K,V>[]中的,是以数组+链表的形式存储的(jdk1.8已经改为数组+链表+红黑树实现了)
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;// 当前的key
V value;// 当前的value
Entry<K,V> next;// 下一个<key, value>
int hash;// hash值
Entry(int h, K k, V v, Entry<K,V> n) {
value = v;
next = n;
key = k;
hash = h;
}
public final K getKey() {
return key;
}
public final V getValue() {
return value;
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
// 判断两个Entry是否相等
public final boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry e = (Map.Entry)o;
Object k1 = getKey();
Object k2 = e.getKey();
if (k1 == k2 || (k1 != null && k1.equals(k2))) {
Object v1 = getValue();
Object v2 = e.getValue();
if (v1 == v2 || (v1 != null && v1.equals(v2)))
return true;
}
return false;
}
// 计算hash值
public final int hashCode() {
return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
}
public final String toString() {
return getKey() + "=" + getValue();
}
// 当向HashMap中添加元素时,会调用recordAccess()。
// 这里不做任何处理
void recordAccess(HashMap<K,V> m) {
}
// 当从HashMap中删除元素时,会调用recordRemoval()。
// 这里不做任何处理
void recordRemoval(HashMap<K,V> m) {
}
// 基础构造方法
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;
threshold = initialCapacity;// 初始化时让 扩容阈值直接等于容量
init();
}
public HashMap(Map<? extends K, ? extends V> m) {
// 把m.size()看作是threshold,最少需要的容量 = threshold / loadFactor + 1
this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
inflateTable(threshold);// 创建hashMap
putAllForCreate(m); // 将元素放进去
}
private void inflateTable(int toSize) {
// 找到一个比toSize大的2的幂
int capacity = roundUpToPowerOf2(toSize);
threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
table = new Entry[capacity];
initHashSeedAsNeeded(capacity);//初始化hash掩码值
}
// 将<key, value>元素放进新的hashMap中
private void putAllForCreate(Map<? extends K, ? extends V> m) {
for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
putForCreate(e.getKey(), e.getValue());
}
private void putForCreate(K key, V value) {
int hash = null == key ? 0 : hash(key);//计算hash值
int i = indexFor(hash, table.length);// 获取下标
// 如果key已存在,则替换掉value值
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
e.value = value;
return;
}
}
createEntry(hash, key, value, i);// 创建Entry并放在链表头
}
// 根据hash值和数组和lenght获取该Entry应该放在的位置的下标
// length必须是2的幂,为什么?
// 2的幂二进制的最后一位一定是0,length-1的二进制最后一位一定是1,h&(length-1)可能是奇数,也可能是偶数
// 如果length不是2的幂,它的二进制表示为 xxxx1(x表示0或1),length-1的二进制为xxxx0,0与任何数与运算一定是0,这就导致了函数返回的下标一定是偶数,既浪费了空间,又增加了hash碰撞的概率
static int indexFor(int h, int length) {
return h & (length-1);
}
// 直接将新加进来的放在链表头
void createEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<>(hash, key, value, e);
size++;
}
public boolean containsKey(Object key) {
return getEntry(key) != null;
}
final Entry<K,V> getEntry(Object key) {
if (size == 0) {
return null;
}
int hash = (key == null) ? 0 : hash(key);
// 还是要for循环链表,也不算是严格个O(1)吧
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 != null && key.equals(k))))
return e;
}
return null;
}
public V put(K key, V value) {
if (table == EMPTY_TABLE) {//如果是空表,直接扩容
inflateTable(threshold);
}
if (key == null) //如果key为null,直接放到table[0]中
return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash, table.length);
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))) { //key重复则替换value
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
void addEntry(int hash, K key, V value, int bucketIndex) {
// size已经不小于threshold,并且还要扩张
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length); // 扩容
hash = (null != key) ? hash(key) : 0; // 重新计算hash值
bucketIndex = indexFor(hash, table.length); // 重新计算下标
}
//创建Entry并将它放在链表头
createEntry(hash, key, value, bucketIndex);
}
// 扩容操作
void resize(int newCapacity) {
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) {// 如果capacity已经不能扩充了,就提升threshold来将就着放吧
threshold = Integer.MAX_VALUE;
return;
}
Entry[] newTable = new Entry[newCapacity];
transfer(newTable, initHashSeedAsNeeded(newCapacity));
table = newTable;
threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}
// copy表,可能需要重新计算hash值
void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
for (Entry<K,V> e : table) {
while(null != e) {
Entry<K,V> next = e.next;
/**
* 注意:这里可能出现死循环
* 因为这里未加锁,多线程情况下同时对同一个table扩容时又对同一个链表重构,就可能出现死循环情况
* 想象一下,在table[i]中,A.next=B,在它准备修正A,B的位置时,另一个线程令B.next=A,此时就造成了死循环
* 关于hashMap死循环,可以看这篇文章:https://www.cnblogs.com/dongguacai/p/5599100.html
*/
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key);
}
int i = indexFor(e.hash, newCapacity);
// ------------------------------------hashMap的安全隐患----------------------------------------------
e.next = newTable[i];// e的下一个十newtable[i]的链表头
newTable[i] = e;//让e作为newTable[i]的链表头
e = next;//下一个
//-----------------------------------------hashMap的安全隐患------------------------------------------
}
}
}