1.JDK1.7 HashMap 数据结构图
解释:每个数组位置,都会存储一个Entry<K,V>键值对对象。
2.涉及基础知识
涉及知识:
位或(|):第一个操作数的的第n位于第二个操作数的第n位 只要有一个是1,那么结果的第n为也为1,
否则为0.
位异或( ^ ):第一个操作数的的第n位于第二个操作数的第n位 相反,那么结果的第n为也为1,
否则为0.
位非( ~ ): 操作数的第n位为1,那么结果的第n位为0,反之。
位与( & ):第一个操作数的的第n位于第二个操作数的第n位如果都是1,那么结果的第n为也为1,否
则为0.
无符号右移( >>> ):正数右移,高位用0补,负数右移,高位用1补,当负数使用无符号右移时,用0
替换部位(自然而然的,就由负数变成了正数了)
右移( >> ):右移2位,高位补0。
左移( << ):左移2位,低位补0。
3.HashMap类,分析成员变量
/**
* 初始容量大小
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* 最大容量大小
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* 加载因子,默认0.75
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* 空的数组实列
*/
static final Entry<?,?>[] EMPTY_TABLE = {};
/**
* 数组,根据需要调整大小。长度必须始终是2的幂。
*/
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
/**
* Entry数组的长度
*/
transient int size;
/**
* 扩容阀值(当数组的长度大于这个值时,会对数组进行扩容)
*/
int threshold;
/**
*哈希表的加载因子
*
*/
final float loadFactor;
/**
* HashMap在结构上被修改的次数,防止多线程新增,遍历,数组结构变化,
* 会有异常ConcurrentModificationException抛出
*/
transient int modCount;
/**
* 数组容量替代阀值(超过该阈值时,可以使用替代哈希)
*/
static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;
3.构造方法(构造方法就只分析无参的了,其它类似)
public HashMap() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR); //DEFAULT_INITIAL_CAPACITY 默认的初始容量,上面已经定义 16 //DEFAULT_LOAD_FACTOR 默认的加载因子0.75f } 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; //初始化加载因子0.75f threshold = initialCapacity; //初始化扩容阀值 init(); //预留给LinkedHashMap }
4. HashMap put方法分析
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold); // 第一次插入数据,进行初始化数组
}
if (key == null)
return putForNullKey(value); //插入的key值为NUll,将数据插入到数组第一位元素
int hash = hash(key); //通过key值计算hash值
int i = indexFor(hash, table.length); //通过hash值计算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))) {
//hash值相等 并且key值相等覆盖原来的值
V oldValue = e.value;
e.value = value;
e.recordAccess(this); //预留给LinkedHashMap实现
return oldValue;
}
}
modCount++; //处理修改key对应的vaue,其它操作都会走到此
addEntry(hash, key, value, i); //插入对应数据(扩容-原数据迁移至新数组都在这里)
return null;
}
void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length); //扩容
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length); //计算当前key存放下标位置
}
createEntry(hash, key, value, bucketIndex); //添加实体
}
private void inflateTable(int toSize) {
// Find a power of 2 >= toSize
int capacity = roundUpToPowerOf2(toSize);//计算容量
//计算数组下次扩容阀值
threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
table = new Entry[capacity]; //初始化entry
initHashSeedAsNeeded(capacity);
}
private static int roundUpToPowerOf2(int number) {
// assert number >= 0 : "number must be non-negative";
return number >= MAXIMUM_CAPACITY
? MAXIMUM_CAPACITY
: (number > 1) ? Integer.highestOneBit((number - 1) << 1) : 1;
}
/**
* 判断 capacity的这个值,根据我所获取到的值来判断需不需要生成hashseed,
* 当 capacity的值大于某个值时,就生成一个hashseed,让hash算法的散列性,更高一点,如果
* 不知道,则hashseed为默认值 Integer.MAX_VALUE
**/
final boolean initHashSeedAsNeeded(int capacity) {
boolean currentAltHashing = hashSeed != 0;
boolean useAltHashing = sun.misc.VM.isBooted() &&
(capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
boolean switching = currentAltHashing ^ useAltHashing;
if (switching) {
hashSeed = useAltHashing
? sun.misc.Hashing.randomHashSeed(this)
: 0;
}
return switching;
}
/**
*计算哈希值
**/
final int hash(Object k) {
int h = hashSeed;
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k); //字符串用这种算法生成哈希
}
h ^= k.hashCode();
//此函数可确保仅在以下方面存在差异的哈希代码
//每个位位置的常数倍数有一个有界
//碰撞次数(默认负载系数约为8次)
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
/**
* 通过hash和数组容量长度确定下标位置
*/
static int indexFor(int h, int length) {
// assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
return h & (length-1);
}
/**
* 插入数据
*/
void addEntry(int hash, K key, V value, int bucketIndex) {
//size table中存储的数据个数 bucketIndex 下标位置
//数据个数大于阀值并且当前下标位置有数据会进行扩容处理
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length); //扩容-迁移原数据
hash = (null != key) ? hash(key) : 0; //重新计算hash
bucketIndex = indexFor(hash, table.length);//重新获取下标
}
//插入数据
createEntry(hash, key, value, bucketIndex);
}
/**
* 扩容处理
*newCapacity 2的幂次方 原来16基础上
**/
void resize(int newCapacity) {
Entry[] oldTable = table; //存放旧的table
int oldCapacity = oldTable.length; //存放旧的table长度
if (oldCapacity == MAXIMUM_CAPACITY) {//如果旧的table长度为最大,则将阀值也改为最大
threshold = Integer.MAX_VALUE;
return;//不进行扩容了
}
Entry[] newTable = new Entry[newCapacity];//新建扩容后的table
transfer(newTable, initHashSeedAsNeeded(newCapacity));//转移旧数据到新table
table = newTable;//更换为新table
//重新计算阀值
threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}
/**
* 数据转移
* newTable 新table(使用头插法将老数据转移到新数据)
*/
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;
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key);
}
int i = indexFor(e.hash, newCapacity);
e.next = newTable[i];
newTable[i] = e;
e = next;
}
}
}