HashMap源码分析
Posted 1900
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HashMap源码分析相关的知识,希望对你有一定的参考价值。
以下内容基于jdk1.7.0_79源码;
什么是HashMap
基于哈希表的一个Map接口实现,存储的对象是一个键值对对象(Entry<K,V>);
HashMap补充说明
基于数组和链表实现,内部维护着一个数组table,该数组保存着每个链表的表头结点;查找时,先通过hash函数计算hash值,再根据hash值计算数组索引,然后根据索引找到链表表头结点,然后遍历查找该链表;
HashMap数据结构
画了个示意图,如下,左边的数组索引是根据hash值计算得到,不同hash值有可能产生一样的索引,即哈希冲突,此时采用链地址法处理哈希冲突,即将所有索引一致的节点构成一个单链表;
HashMap继承的类与实现的接口
Map接口,方法的含义很简单,基本上看个方法名就知道了,后面会在HashMap源码分析里详细说明
AbstractMap抽象类中定义的方法
HashMap源码分析,大部分都加了注释
package java.util;
import java.io.*;
public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
{
/**
* 默认初始容量,默认为2的4次方 = 16
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* 最大容量,默认为1的30次方
*/
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;
/**
* 当前Map中key-value映射的个数
*/
transient int size;
/**
* 下次扩容阈值,当size > capacity * load factor
*/
int threshold;
/**
* 负载因子
*/
final float loadFactor;
/**
* Hash表结构性修改次数,用于实现迭代器快速失败行为
*/
transient int modCount;
/**
* 容量阈值,默认大小为Integer.MAX_VALUE
*/
static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;
/**
* 静态内部类Holder,存放一些只能在虚拟机启动后才能初始化的值
*/
private static class Holder {
/**
* 容量阈值
*/
static final int ALTERNATIVE_HASHING_THRESHOLD;
static {
//获取系统变量jdk.map.althashing.threshold
String altThreshold = java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction(
"jdk.map.althashing.threshold"));
int threshold;
try {
threshold = (null != altThreshold)
? Integer.parseInt(altThreshold)
: ALTERNATIVE_HASHING_THRESHOLD_DEFAULT;
// jdk.map.althashing.threshold系统变量默认为-1,如果为-1,则将阈值设为Integer.MAX_VALUE
if (threshold == -1) {
threshold = Integer.MAX_VALUE;
}
//阈值需要为正数
if (threshold < 0) {
throw new IllegalArgumentException("value must be positive integer.");
}
} catch(IllegalArgumentException failed) {
throw new Error("Illegal value for ‘jdk.map.althashing.threshold‘", failed);
}
ALTERNATIVE_HASHING_THRESHOLD = threshold;
}
}
/**
* A randomizing value associated with this instance that is applied to
* hash code of keys to make hash collisions harder to find. If 0 then
* alternative hashing is disabled.
*/
transient int hashSeed = 0;
/**
* 生成一个空的HashMap,并指定其容量大小和负载因子
*
* @param initialCapacity 初始容量大小
* @param loadFactor 负载因子
* @throws IllegalArgumentException 当参数为无效的时候
*/
public HashMap(int initialCapacity, float loadFactor) {
//保证初始容量大于等于0
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
//保证初始容量不大于最大容量MAXIMUM_CAPACITY
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
//loadFactor小于0或为无效数字
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
//负载因子
this.loadFactor = loadFactor;
//下次扩容大小
threshold = initialCapacity;
init();
}
/**
* 生成一个空的HashMap,并指定其容量大小,负载因子使用默认的0.75
*
* @param initialCapacity 初始容量大小
* @throws IllegalArgumentException
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
* 生成一个空的HashMap,容量大小使用默认值16,负载因子使用默认值0.75
*/
public HashMap() {
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}
/**
* 根据指定的map生成一个新的HashMap,负载因子使用默认值,初始容量大小为Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,DEFAULT_INITIAL_CAPACITY)
* @param m the map whose mappings are to be placed in this map
* @throws NullPointerException if the specified map is null
*/
public HashMap(Map<? extends K, ? extends V> m) {
this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
inflateTable(threshold);
putAllForCreate(m);
}
//返回>=number的最小2的n次方值,如number=5,则返回8
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;
}
/**
* 对table扩容
*/
private void inflateTable(int toSize) {
// Find a power of 2 >= toSize
//找一个值(2的n次方,且>=toSize)
int capacity = roundUpToPowerOf2(toSize);
//下次扩容阈值
threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
table = new Entry[capacity];
initHashSeedAsNeeded(capacity);
}
// internal utilities
/**
* Initialization hook for subclasses. This method is called
* in all constructors and pseudo-constructors (clone, readObject)
* after HashMap has been initialized but before any entries have
* been inserted. (In the absence of this method, readObject would
* require explicit knowledge of subclasses.)
*/
void init() {
}
/**
* Initialize the hashing mask value. We defer initialization until we
* really need it.
*/
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;
}
/**
* 生成hash值
*/
final int hash(Object k) {
int h = hashSeed;
//如果key是字符串,调用un.misc.Hashing.stringHash32生成hash值,不调用String的
//Oracle表示能生成更好的hash分布,不过这在jdk8中已删除
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
//一次散列,调用k的hashCode方法,获取hash值
h ^= k.hashCode();
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
//二次散列,
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);
}
/**
* 返回key-value映射个数
*/
public int size() {
return size;
}
/**
* 判断map是否为空
*/
public boolean isEmpty() {
return size == 0;
}
/**
* 返回指定key对应的value
*/
public V get(Object key) {
//key为null情况
if (key == null)
return getForNullKey();
//根据key查找节点
Entry<K,V> entry = getEntry(key);
//返回key对应的值
return null == entry ? null : entry.getValue();
}
/**
* 查找key为null的value,注意如果key为null,则其hash值为0,默认是放在table[0]里的
*/
private V getForNullKey() {
if (size == 0) {
return null;
}
//在table[0]的链表上查找key为null的键值对,因为null默认是存在table[0]的桶里
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null)
return e.value;
}
return null;
}
/**
*判断是否包含指定的key
*/
public boolean containsKey(Object key) {
return getEntry(key) != null;
}
/**
* 根据key查找键值对,找不到返回null
*/
final Entry<K,V> getEntry(Object key) {
if (size == 0) {
return null;
}
//如果key为null,hash值为0,否则调用hash方法,对key生成hash值
int hash = (key == null) ? 0 : hash(key);
//调用indexFor方法生成hash值的索引,遍历该索引下的链表,查找key“相等”的键值对
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 !=