, Cloneable, Serializable
{
/** * The default initial capacity - MUST be a power of two.*/
//DEFAULT_INITIAL_CAPACITY = 1 << 4;(左移4位,其实质 等于 1*(2^4)= 16)
//----> 链表数组的默认初始化容量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
//------> 链表数组的最大容量 1<<30 = 1*20^30
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* The load factor used when none specified in constructor.
*/
//-----> 默认加载因子 0.75f(数组length >= 16*0.75=12(数组的阈值)时,HashMap就需要扩容)
//默认负载因子,当容器使用率达到这个75%的时候就扩容
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* An empty table instance to share when the table is not inflated.
*/
//-----> EMPTY_TABLE 定义一个空集合
//当数组表还没扩容的时候,一个共享的空表对象
static final Entry,?>[] EMPTY_TABLE = {};
/**
* The table, resized as necessary. Length MUST Always be a power of two.
*/
//不可以序列化的 table,默认是一个空数组
//内部数组表,用来装entry,大小只能是2的n次方。
transient Entry[] table = (Entry[]) EMPTY_TABLE;
/**
* The number of key-value mappings contained in this map.
*/
// 数组的size 是数组的length
//存储的键值对的个数
transient int size;
/**
* The next size value at which to resize (capacity * load factor).
* @serial
*/
// If table == EMPTY_TABLE then this is the initial capacity at which the
// table will be created when inflated.
//threshold 为扩容的阈值 threshold = capacity * load factor (默认阈值 = 初始化容量(默认初始化容量16) * 0.75 = //12)
/**
* 扩容的临界点,如果当前容量达到该值,则需要扩容了。
* 如果当前数组容量为0时(空数组),则该值作为初始化内部数组的初始容量
*/
int threshold;
/**
* The load factor for the hash table.
*
* @serial
*/
//由构造函数传入的指定负载因子
final float loadFactor;
/**
* The number of times this HashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the HashMap or otherwise modify its internal structure (e.g.,
* rehash). This field is used to make iterators on Collection-views of
* the HashMap fail-fast. (See ConcurrentModificationException).
*/
//Hash的修改次数
transient int modCount;
/**
* The default threshold of map capacity above which alternative hashing is
* used for String keys. Alternative hashing reduces the incidence of
* collisions due to weak hash code calculation for String keys.
*
* This value may be overridden by defining the system property
* {@code jdk.map.althashing.threshold}. A property value of {@code 1}
* forces alternative hashing to be used at all times whereas
* {@code -1} value ensures that alternative hashing is never used.
*/
//threshold的最大值
static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;
/**
* holds values which can't be initialized until after VM is booted.
*/
/**
* 静态内部类,提供一些静态常量
*/
private static class Holder {
/**
* Table capacity above which to switch to use alternative hashing.
*/
/**
* 容量阈值,初始化hashSeed的时候会用到该值
*/
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;
// disable alternative hashing if -1
// 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.
*/
//计算hash值时候用,初始是0
transient int hashSeed = 0;
/**
* Constructs an empty HashMap with the specified initial
* capacity and load factor.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
/**
* 生成一个空HashMap,传入容量与负载因子
* @param initialCapacity 初始容量
* @param loadFactor 负载因子
*/
public HashMap(int initialCapacity, float loadFactor) {
//初始容量不能小于0
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
//初始容量不能大于默认的最大容量
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
//负载因子不能小于0,且不能为“NaN”(NaN(“不是一个数字(Not a Number)”的缩写))
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
//将传入的负载因子赋值给属性
this.loadFactor = loadFactor;
//此时并不会创建容器,因为没有 传具体值
// 没下次扩容大小
/**
* 此时并不会创建容器,因为没有传具体值。
* 当下次传具体值的时候,才会“根据这次的初始容量”,创建一个内部数组。
* 所以此次的初始容量只是作为下一次扩容(新建)的容量。
*/
threshold = initialCapacity;
//该方法只在LinkedHashMap中有实现,主要在构造函数初始化和clone、readObject中有调用。
init();
}
/**
* Constructs an empty HashMap with the specified initial
* capacity and the default load factor (0.75).
*
* @param initialCapacity the initial capacity.
* @throws IllegalArgumentException if the initial capacity is negative.
*/
/**
* 生成一个空hashmap,传入初始容量,负载因子使用默认值(0.75)
* @param initialCapacity 初始容量
*/
public HashMap(int initialCapacity) {
//生成空数组,并指定扩容值
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
* Constructs an empty HashMap with the default initial capacity
* (16) and the default load factor (0.75).
*/
/**
* 生成一个空hashmap,初始容量和负载因子全部使用默认值。
*/
public HashMap() {
//生成空数组,并指定扩容值,默认this(16,0.75);
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}
/**
* Constructs a new HashMap with the same mappings as the
* specified Map. The HashMap is created with
* default load factor (0.75) and an initial capacity sufficient to
* hold the mappings in the specified Map.
*
* @param m the map whose mappings are to be placed in this map
* @throws NullPointerException if the specified map is null
*/
/**
* 根据已有map对象生成一个hashmap,初始容量与传入的map相关,负载因子使用默认值
* @param m Map对象
*/
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);
//将传入map的键值对添加到初始数组中
putAllForCreate(m);
}
/**
* 找到number的最小的2的n次方
* @param number
* @return
*/
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;
}
/**
* Inflates the table.
*/
/**
* 新建一个空的内部数组
* @param toSize 新数组容量
*/
private void inflateTable(int toSize) {
// Find a power of 2 >= toSize
//内部数组的大小必须是2的n次方,所以要找到“大于”toSize的“最小的2的n次方”。
int capacity = roundUpToPowerOf2(toSize);
//下次扩容临界值
threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
table = new Entry[capacity];
//根据数组长度初始化hashseed
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.)
*/
/**
* 只在LinkedHashMap中有实现,主要在构造函数初始化和clone、readObject中有调用。
*/
void init() {
}
/**
* Initialize the hashing mask value. We defer initialization until we
* really need it.
*/
/**
* 根据内部数组长度初始化hashseed
* @param capacity 内部数组长度
* @return hashSeed是否初始化
*/
final boolean initHashSeedAsNeeded(int capacity) {
boolean currentAltHashing = hashSeed != 0;
boolean useAltHashing = sun.misc.VM.isBooted() &&
(capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
boolean switching = currentAltHashing ^ useAltHashing;
//为true则赋初始化值
if (switching) {
hashSeed = useAltHashing
? sun.misc.Hashing.randomHashSeed(this)
: 0;
}
return switching;
}
/**
* Retrieve object hash code and applies a supplemental hash function to the
* result hash, which defends against poor quality hash functions. This is
* critical because HashMap uses power-of-two length hash tables, that
* otherwise encounter collisions for hashCodes that do not differ
* in lower bits. Note: Null keys always map to hash 0, thus index 0.
*/
/**
* 根据传入的key生成hash值
* @param k 键值名
* @return hash值
*/
final int hash(Object k) {
int h = hashSeed;
//如果key是字符串类型,就使用stringHash32来生成hash值
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
//一次散列
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);
}
/**
* Returns index for hash code h.
*/
/**
* 返回hash值的索引,采用除模取余法,h & (length-1)操作 等价于 hash % length操作, 但&操作性能更优
*/
/**
* 根据key的hash值与数组长度,找到该key在table数组中的下标
* @param h hash值
* @param length 数组长度
* @return 下标
*/
static int indexFor(int h, int length) {
// assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
//除模取余,相当于hash % length,&速度更快
return h & (length-1);
}
/**
* Returns the number of key-value mappings in this map.
*
* @return the number of key-value mappings in this map
*/
/**
* 返回此hashmap中存储的键值对个数
* @return 键值对个数
*/
public int size() {
return size;
}
/**
* Returns true if this map contains no key-value mappings.
*
* @return true if this map contains no key-value mappings
*/
/**
* 判断hashmap是否为空
* @return true为空,false为非空
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
*
A return value of {@code null} does not necessarily
* indicate that the map contains no mapping for the key; it's also
* possible that the map explicitly maps the key to {@code null}.
* The {@link #containsKey containsKey} operation may be used to
* distinguish these two cases.
*
* @see #put(Object, Object)
*/
/**
* 根据key找到对应value
* @param key 键值名
* @return 键值value
*/
public V get(Object key) {
//如果key为null,则从table[0]中取value
if (key == null)
return getForNullKey();
//如果key不为null,则先根据key,找到其entry
Entry entry = getEntry(key);
//返回entry节点里的value值
return null == entry ? null : entry.getValue();
}
/**
* Offloaded version of get() to look up null keys. Null keys map
* to index 0. This null case is split out into separate methods
* for the sake of performance in the two most commonly used
* operations (get and put), but incorporated with conditionals in
* others.
*/
/**
* 查找key为null的value
* (如果key为null,则hash值为0,并被保存在table[0]中)
* @return 对应value
*/
private V getForNullKey() {
if (size == 0) {
return null;
}
//查找table[0]处的链表,如果找到entry的key为null,就返回其value
for (Entry e = table[0]; e != null; e = e.next) {
if (e.key == null)
return e.value;
}
return null;
}
/**
* Returns true if this map contains a mapping for the
* specified key.
*
* @param key The key whose presence in this map is to be tested
* @return true if this map contains a mapping for the specified
* key.
*/
/**
* 判断指定key是否存在
* @param key 键值名
* @return 存在则返回true
*/
public boolean containsKey(Object key) {
return getEntry(key) != null;
}
/**
* Returns the entry associated with the specified key in the
* HashMap. Returns null if the HashMap contains no mapping
* for the key.
*/
/**
* 根据key值查找所属entry节点
* @param key 键值名
* @return entry节点
*/
final Entry getEntry(Object key) {
if (size == 0) {
return null;
}
//如果key为null,则其hash值为0,否则计算hash值
int hash = (key == null) ? 0 : hash(key);
//根据hash值找到table下标,然后迭代该下标中的链表里的每一个entry节点
for (Entry 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;
}
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with key, or
* null if there was no mapping for key.
* (A null return can also indicate that the map
* previously associated null with key.)
*/
/**
* 存入一个键值对,如果key重复,则更新value
* @param key 键值名
* @param value 键值
* @return 如果存的是新key则返回null,如果覆盖了旧键值对,则返回旧value
*/
public V put(K key, V value) {
//如果数组为空,则新建数组
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
//如果key为null,则把value放在table[0]中
if (key == null)
return putForNullKey(value);
//生成key所对应的hash值
int hash = hash(key);
//根据hash值和数组的长度找到数组下标index i:该key所属entry在table中的位置i
int i = indexFor(hash, table.length);
/**
* 数组中每一项存的都是一个链表,
* 先找到i位置,然后循环该位置上的每一个entry,
* 如果发现存在key与传入key相等,则替换其value。然后结束侧方法。
* 如果没有找到相同的key,则继续执行下一条指令,将此键值对存入链表头
*/
for (Entry e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
//map操作次数加一
modCount++;
//查看是否需要扩容,并将该键值对存入指定下标的链表头中
addEntry(hash, key, value, i);
//如果是新存入的键值对,则返回null
return null;
}
/**
* Offloaded version of put for null keys
*/
/**
* 如果key为null,则将其value存入table[0]的链表中
* @param value 键值
* @return 如果覆盖了旧value,则返回value,否则返回null
*/
private V putForNullKey(V value) {
//迭代table[0]中的链表里的每一个entry
for (Entry e = table[0]; e != null; e = e.next) {
//如果找到key为null的entry,则覆盖其value,并返回旧value
if (e.key == null) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
//操作次数加一
modCount++;
//查看是否需要扩容,然后将entry插入table的指定下标中的链表头中
addEntry(0, null, value, 0);
return null;
}
/**
* This method is used instead of put by constructors and
* pseudoconstructors (clone, readObject). It does not resize the table,
* check for comodification, etc. It calls createEntry rather than
* addEntry.
*/
/**
* 添加键值对
* @param key 键值名
* @param value 键值
*/
private void putForCreate(K key, V value) {
//如果key为null,则hash值为0,否则根据key计算hash值
int hash = null == key ? 0 : hash(key);
//根据hash值和数组的长度找到:该key所属entry在table中的位置i
int i = indexFor(hash, table.length);
/**
* Look for preexisting entry for key. This will never happen for
* clone or deserialize. It will only happen for construction if the
* input Map is a sorted map whose ordering is inconsistent w/ equals.
*/
/**
* 数组中每一项存的都是一个链表,
* 先找到i位置,然后循环该位置上的每一个entry,
* 如果发现存在key与传入key相等,则替换其value。然后结束此方法。
* 如果没有找到相同的key,则继续执行下一条指令,将此键值对存入链表头
*/
for (Entry 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);
}
/**
* 添加指定map里面的所有键值对
* @param m
*/
private void putAllForCreate(Map extends K, ? extends V> m) {
for (Map.Entry extends K, ? extends V> e : m.entrySet())
putForCreate(e.getKey(), e.getValue());
}
/**
* Rehashes the contents of this map into a new array with a
* larger capacity. This method is called automatically when the
* number of keys in this map reaches its threshold.
*
* If current capacity is MAXIMUM_CAPACITY, this method does not
* resize the map, but sets threshold to Integer.MAX_VALUE.
* This has the effect of preventing future calls.
*
* @param newCapacity the new capacity, MUST be a power of two;
* must be greater than current capacity unless current
* capacity is MAXIMUM_CAPACITY (in which case value
* is irrelevant).
*/
/**
* 对数组扩容,即创建一个新数组,并将旧数组里的东西重新存入新数组
* @param newCapacity 新数组容量
*/
void resize(int newCapacity) {
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
//如果当前数组容量已经达到最大值了,则将扩容的临界值设置为Integer.MAX_VALUE(Integer.MAX_VALUE是容量的临界点)
if (oldCapacity == MAXIMUM_CAPACITY) {
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);
}
/**
* Transfers all entries from current table to newTable.
*/
/**
* 将现有数组中的内容重新通过hash计算存入新数组
* @param newTable 新数组
* @param rehash
*/
void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
//遍历现有数组中的每一个单链表的头entry
for (Entry e : table) {
//查找链表里的每一个entry
while(null != e) {
Entry next = e.next;
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key);
}
//根据新的数组长度,重新计算此entry所在下标i
int i = indexFor(e.hash, newCapacity);
//将entry放入下标i处链表的头部(将新数组此处的原有链表存入entry的next指针)
e.next = newTable[i];
//将链表存回下标i
newTable[i] = e;
//查看下一个entry
e = next;
}
}
}
/**
* Copies all of the mappings from the specified map to this map.
* These mappings will replace any mappings that this map had for
* any of the keys currently in the specified map.
*
* @param m mappings to be stored in this map
* @throws NullPointerException if the specified map is null
*/
/**
* 将传入map的所有键值对存入本map
* @param m 传入map
*/
public void putAll(Map extends K, ? extends V> m) {
//传入数组的键值对数
int numKeysToBeAdded = m.size();
if (numKeysToBeAdded == 0)
return;
//如果本地数组为空,则新建本地数组
if (table == EMPTY_TABLE) {
//从当前扩容临界值和传入数组的容量中选择大的一方作为初始数组容量
inflateTable((int) Math.max(numKeysToBeAdded * loadFactor, threshold));
}
/*
* Expand the map if the map if the number of mappings to be added
* is greater than or equal to threshold. This is conservative; the
* obvious condition is (m.size() + size) >= threshold, but this
* condition could result in a map with twice the appropriate capacity,
* if the keys to be added overlap with the keys already in this map.
* By using the conservative calculation, we subject ourself
* to at most one extra resize.
*/
//如果传入map的键值对数比“下一次扩容后的内部数组大小”还大,则对数组进行扩容。(因为当前数组即使扩容后也装不下它)
if (numKeysToBeAdded > threshold) {
//确定新内部数组所需容量
int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
//不能大于最大容量
if (targetCapacity > MAXIMUM_CAPACITY)
targetCapacity = MAXIMUM_CAPACITY;
//当前数组长度
int newCapacity = table.length;
//从当前数组长度开始增加,每次增加一个“2次方”,直到大于所需容量为止
while (newCapacity < targetCapacity)
newCapacity <<= 1;
//如果发现内部数组长度需要增加,则扩容内部数组
if (newCapacity > table.length)
resize(newCapacity);
}
//遍历传入map,将键值对存入内部数组
for (Map.Entry extends K, ? extends V> e : m.entrySet())
put(e.getKey(), e.getValue());
}
/**
* Removes the mapping for the specified key from this map if present.
*
* @param key key whose mapping is to be removed from the map
* @return the previous value associated with key, or
* null if there was no mapping for key.
* (A null return can also indicate that the map
* previously associated null with key.)
*/
/**
* 根据key删除entry节点
* @param key 被删除的entry的key值
* @return 被删除的节点的value,删除失败则返回null
*/
public V remove(Object key) {
Entry e = removeEntryForKey(key);
return (e == null ? null : e.value);
}
/**
* Removes and returns the entry associated with the specified key
* in the HashMap. Returns null if the HashMap contains no mapping
* for this key.
*/
/**
* 根据key删除entry节点
* @param key 被删除的entry的key值
* @return 被删除的节点,删除失败则返回null
*/
final Entry removeEntryForKey(Object key) {
if (size == 0) {
return null;
}
//计算key的hash值
int hash = (key == null) ? 0 : hash(key);
//计算所属下标
int i = indexFor(hash, table.length);
//找到下标所存储的单链表的头节点
Entry prev = table[i];
Entry e = prev;
//迭代单链表找到要删除的节点
while (e != null) {
Entry next = e.next;
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
modCount++;
size--;
if (prev == e)
table[i] = next;
else
prev.next = next;
e.recordRemoval(this);
return e;
}
prev = e;
e = next;
}
return e;
}
/**
* Special version of remove for EntrySet using {@code Map.Entry.equals()}
* for matching.
*/
/**
* 删除指定entry节点
* @param o 需要被删除的节点
* @return 如果删除失败返回null,删除成功
*/
final Entry removeMapping(Object o) {
if (size == 0 || !(o instanceof Map.Entry))
return null;
Map.Entry entry = (Map.Entry) o;
Object key = entry.getKey();
int hash = (key == null) ? 0 : hash(key);
//得到数组索引
int i = indexFor(hash, table.length);
Entry prev = table[i];
Entry e = prev;
//开始遍历该单链表
while (e != null) {
Entry next = e.next;
//找到节点
if (e.hash == hash && e.equals(entry)) {
modCount++;
size--;
if (prev == e)
table[i] = next;
else
prev.next = next;
e.recordRemoval(this);
return e;
}
prev = e;
e = next;
}
return e;
}
/**
* Removes all of the mappings from this map.
* The map will be empty after this call returns.
*/
/**
* 删除hashmap中的所有元素
*/
public void clear() {
modCount++;
//将table中的每一个元素都设置成null
Arrays.fill(table, null);
size = 0;
}
/**
* Returns true if this map maps one or more keys to the
* specified value.
*
* @param value value whose presence in this map is to be tested
* @return true if this map maps one or more keys to the
* specified value
*/
/**
* 判断是否含有指定value
* @param value 键值
* @return 含有则返回true
*/
public boolean containsValue(Object value) {
//如果value为null,则判断是否含有value为null的键值对
if (value == null)
return containsNullValue();
Entry[] tab = table;
//遍历table,找遍每条链表
for (int i = 0; i < tab.length ; i++)
for (Entry e = tab[i] ; e != null ; e = e.next)
if (value.equals(e.value))
return true;
return false;
}
/**
* Special-case code for containsValue with null argument
*/
/**
* 判断是否含有value为null的键值对
* @return 含有则返回true
*/
private boolean containsNullValue() {
Entry[] tab = table;
for (int i = 0; i < tab.length ; i++)
for (Entry e = tab[i] ; e != null ; e = e.next)
if (e.value == null)
return true;
return false;
}
/**
* Returns a shallow copy of this HashMap instance: the keys and
* values themselves are not cloned.
*
* @return a shallow copy of this map
*/
/**
* 生成一个新的hashmap对象,新hashmap中数组也是新生成的,
* 但数组中的entry节点还是引用旧hashmap中的元素。
* 所以对目前已有的节点进行修改会导致:原对象和clone对象都发生改变。
* 但进行新增或删除就不会影响对方,因为这相当于是对数组做出的改变,clone对象新生成了一个数组。
* @return clone出的hashmap
*/
public Object clone() {
HashMap result = null;
try {
result = (HashMap)super.clone();
} catch (CloneNotSupportedException e) {
// assert false;
}
if (result.table != EMPTY_TABLE) {
result.inflateTable(Math.min(
(int) Math.min(
size * Math.min(1 / loadFactor, 4.0f),
// we have limits...
HashMap.MAXIMUM_CAPACITY),
table.length));
}
result.entrySet = null;
result.modCount = 0;
result.size = 0;
result.init();
result.putAllForCreate(this);
return result;
}
/**
* 内部类 Entry
* hashmap中
每一个键值对都是存在
Entry对象中,entry还存储了自己的hash值等信息
* Entry被储存在hashmap的内部数组中。
* @param 键值名key
* @param 键值value
*/
static class Entry implements Map.Entry {
final K key;//key
V value;//key-value对应的值
//数组中每一项(链表)可能存储多个entry(key-value键值对、hash(key)、next),而这些entry就是以链表的形式被存储,此next指向下一个entry
Entry next;//链表中下一个entry对象的地址值(类似于c的指针)
int hash;//hash值
/**
* Creates new entry.
*/
//初始化节点
Entry(int h, K k, V v, Entry n) {
value = v;
next = n;
key = k;
hash = h;
}
//获取节点的key
public final K getKey() {
return key;
}
//获取节点的value
public final V getValue() {
return value;
}
//设置新value,并返回旧的value
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
//判断传入节点与此结点的“key”和“value”是否相等。都相等则返回true
public final boolean equals(Object o) {
//如果传入对象不是Entry,则返回false
if (!(o instanceof Map.Entry))
return false;
Map.Entry e = (Map.Entry)o;
Object k1 = getKey();//
Object k2 = e.getKey();//传入的key
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;
}
//根据key和value的值生成hashCode
public final int hashCode() {
return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
}
public final String toString() {
return getKey() + "=" + getValue();
}
/**
* This method is invoked whenever the value in an entry is
* overwritten by an invocation of put(k,v) for a key k that's already
* in the HashMap.
*/
//每当相同key的value被覆盖时被调用一次,在HashMap的子类LinkedHashMap中实现了这个方法
void recordAccess(HashMap m) {
}
/**
* This method is invoked whenever the entry is
* removed from the table.
*/
//每移除一个entry就被调用一次,在HashMap的子类LinkedHashMap中实现了这个方法;
void recordRemoval(HashMap m) {
}
}
/**
* Adds a new entry with the specified key, value and hash code to
* the specified bucket. It is the responsibility of this
* method to resize the table if appropriate.
*
* Subclass overrides this to alter the behavior of put method.
*/
/**
* 查看是否需要扩容,然后添加新节点
* @param hash key的hash值
* @param key 结点内key
* @param value 结点内value
* @param bucketIndex 结点所在的table下标
*/
void addEntry(int hash, K key, V value, int bucketIndex) {
//如果当前键值对数量达到了临界值,或目标table下标不存在,则扩容table
if ((size >= threshold) && (null != table[bucketIndex])) {
//容量扩容一倍
resize(2 * table.length);
//由于数组扩容了,重新计算hash值
hash = (null != key) ? hash(key) : 0;
//重新计算存储位置
bucketIndex = indexFor(hash, table.length);
}
//将键值对与他的hash值作为一个entry,插入table的指定下标中的链表头中
createEntry(hash, key, value, bucketIndex);
}
/**
* Like addEntry except that this version is used when creating entries
* as part of Map construction or "pseudo-construction" (cloning,
* deserialization). This version needn't worry about resizing the table.
*
* Subclass overrides this to alter the behavior of HashMap(Map),
* clone, and readObject.
*/
/**
* 将键值对与他的hash值作为一个entry,插入table的指定下标中的链表头中
*// 新增Entry。将“key-value”插入指定位置,bucketIndex是位置索引(数组下标)。
* @param hash hash值
* @param key 键值名
* @param value 键值
* @param bucketIndex 被插入的下标
*/
void createEntry(int hash, K key, V value, int bucketIndex) {
// 保存“bucketIndex”位置的Entry值到“e”(Entry类中的next)中
Entry e = table[bucketIndex];
// ***设置“bucketIndex”位置的元素为“新Entry”,
// ***设置“e”为“新Entry的下一个节点”
table[bucketIndex] = new Entry<>(hash, key, value, e);
size++;
}
/**
* 所有迭代器的抽象父类
* @param 存储的数据的类型
*/
private abstract class HashIterator implements Iterator {
//指向下一个节点
Entry next; // next entry to return
int expectedModCount; // For fast-fail // 用于判断快速失败行为
int index; // current slot //当前table下标
Entry current; // current entry //当前entry节点
/**
* 构造函数
* 使expectedModCount = modCount相等
*/
HashIterator() {
expectedModCount = modCount;
if (size > 0) { // advance to first entry
Entry[] t = table;
while (index < t.length && (next = t[index++]) == null)
;
}
}
public final boolean hasNext() {
return next != null;
}
final Entry nextEntry() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
Entry e = next;
if (e == null)
throw new NoSuchElementException();
if ((next = e.next) == null) {
Entry[] t = table;
while (index < t.length && (next = t[index++]) == null)
;
}
current = e;
return e;
}
public void remove() {
if (current == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
Object k = current.key;
current = null;
HashMap.this.removeEntryForKey(k);
expectedModCount = modCount;
}
}
//ValueIterator迭代器
private final class ValueIterator extends HashIterator {
public V next() {
return nextEntry().value;
}
}
//KeyIterator迭代器
private final class KeyIterator extends HashIterator {
public K next() {
return nextEntry().getKey();
}
}
//KeyIterator迭代器
private final class EntryIterator extends HashIterator> {
public Map.Entry next() {
return nextEntry();
}
}
// Subclass overrides these to alter behavior of views' iterator() method
// 返回各种迭代器对象
Iterator newKeyIterator() {
return new KeyIterator();
}
Iterator newValueIterator() {
return new ValueIterator();
}
Iterator> newEntryIterator() {
return new EntryIterator();
}
// Views
//含有所有entry节点的一个set集合
private transient Set> entrySet = null;
/**
* Returns a {@link Set} view of the keys contained in this map.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through
* the iterator's own remove operation), the results of
* the iteration are undefined. The set supports element removal,
* which removes the corresponding mapping from the map, via the
* Iterator.remove, Set.remove,
* removeAll, retainAll, and clear
* operations. It does not support the add or addAll
* operations.
*/
/**
* 返回一个set集合,里面装的都是hashmap的value。
* 因为map中的key不能重复,set集合中的值也不能重复,所以可以装入set。
*
* 在hashmap的父类AbstractMap中,定义了Set keySet = null;
* 如果keySet为null,则返回内部类KeySet。
* @return 含有所有key的set集合
*/
public Set keySet() {
Set ks = keySet;
return (ks != null ? ks : (keySet = new KeySet()));
}
/**
* 内部类,生成一个set集合,里面装有此hashmap的所有key。
*/
private final class KeySet extends AbstractSet {
public Iterator iterator() {
return newKeyIterator();
}
public int size() {
return size;
}
public boolean contains(Object o) {
return containsKey(o);
}
public boolean remove(Object o) {
return HashMap.this.removeEntryForKey(o) != null;
}
public void clear() {
HashMap.this.clear();
}
}
/**
* Returns a {@link Collection} view of the values contained in this map.
* The collection is backed by the map, so changes to the map are
* reflected in the collection, and vice-versa. If the map is
* modified while an iteration over the collection is in progress
* (except through the iterator's own remove operation),
* the results of the iteration are undefined. The collection
* supports element removal, which removes the corresponding
* mapping from the map, via the Iterator.remove,
* Collection.remove, removeAll,
* retainAll and clear operations. It does not
* support the add or addAll operations.
*/
/**
* 返回一个Collection集合,里面装的都是hashmap的value。
* 因为map中的value可以重复,所以装入Collection。
*
* 在hashmap的父类AbstractMap中,定义了Collection values = null;
* 如果values为null,则返回内部类Values。
*/
public Collection values() {
Collection vs = values;
return (vs != null ? vs : (values = new Values()));
}
/**
* 内部类,生成一个Collection集合,里面装有此hashmap的所有value
*/
private final class Values extends AbstractCollection {
public Iterator iterator() {
return newValueIterator();
}
public int size() {
return size;
}
public boolean contains(Object o) {
return containsValue(o);
}
public void clear() {
HashMap.this.clear();
}
}
/**
* Returns a {@link Set} view of the mappings contained in this map.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through
* the iterator's own remove operation, or through the
* setValue operation on a map entry returned by the
* iterator) the results of the iteration are undefined. The set
* supports element removal, which removes the corresponding
* mapping from the map, via the Iterator.remove,
* Set.remove, removeAll, retainAll and
* clear operations. It does not support the
* add or addAll operations.
*
* @return a set view of the mappings contained in this map
*/
/**
* 返回一个set集合,里面装的是所有的entry结点
* (相当于把map集合转化成set集合)
* @return 含有所有entry的set集合
*/
public Set> entrySet() {
return entrySet0();
}
/**
* 如果entrySet为null,则返回一个含有所有entry节点的一个set集合
* @return 含有所有entry节点的一个set集合
*/
private Set> entrySet0() {
Set> es = entrySet;
return es != null ? es : (entrySet = new EntrySet());
}
/**
* 内部类,含有所有entry节点的一个set集合
*/
private final class EntrySet extends AbstractSet> {
//返回迭代器
public Iterator> iterator() {
return newEntryIterator();
}
//查找传入entry是否存在
public boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry e = (Map.Entry) o;
Entry candidate = getEntry(e.getKey());
return candidate != null && candidate.equals(e);
}
//删除
public boolean remove(Object o) {
return removeMapping(o) != null;
}
//返回键值对数
public int size() {
return size;
}
//清空
public void clear() {
HashMap.this.clear();
}
}
/**
* Save the state of the HashMap instance to a stream (i.e.,
* serialize it).
*
* @serialData The capacity of the HashMap (the length of the
* bucket array) is emitted (int), followed by the
* size (an int, the number of key-value
* mappings), followed by the key (Object) and value (Object)
* for each key-value mapping. The key-value mappings are
* emitted in no particular order.
*/
private void writeObject(java.io.ObjectOutputStream s)
throws IOException
{
// Write out the threshold, loadfactor, and any hidden stuff
s.defaultWriteObject();
// Write out number of buckets
if (table==EMPTY_TABLE) {
s.writeInt(roundUpToPowerOf2(threshold));
} else {
s.writeInt(table.length);
}
// Write out size (number of Mappings)
s.writeInt(size);
// Write out keys and values (alternating)
if (size > 0) {
for(Map.Entry e : entrySet0()) {
s.writeObject(e.getKey());
s.writeObject(e.getValue());
}
}
}
private static final long serialVersionUID = 362498820763181265L;
/**
* Reconstitute the {@code HashMap} instance from a stream (i.e.,
* deserialize it).
*/
private void readObject(java.io.ObjectInputStream s)
throws IOException, ClassNotFoundException
{
// Read in the threshold (ignored), loadfactor, and any hidden stuff
s.defaultReadObject();
if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
throw new InvalidObjectException("Illegal load factor: " +
loadFactor);
}
// set other fields that need values
table = (Entry[]) EMPTY_TABLE;
// Read in number of buckets
s.readInt(); // ignored.
// Read number of mappings
int mappings = s.readInt();
if (mappings < 0)
throw new InvalidObjectException("Illegal mappings count: " +
mappings);
// capacity chosen by number of mappings and desired load (if >= 0.25)
int capacity = (int) Math.min(
mappings * Math.min(1 / loadFactor, 4.0f),
// we have limits...
HashMap.MAXIMUM_CAPACITY);
// allocate the bucket array;
if (mappings > 0) {
inflateTable(capacity);
} else {
threshold = capacity;
}
init(); // Give subclass a chance to do its thing.
// Read the keys and values, and put the mappings in the HashMap
for (int i = 0; i < mappings; i++) {
K key = (K) s.readObject();
V value = (V) s.readObject();
putForCreate(key, value);
}
}
// These methods are used when serializing HashSets
int capacity() { return table.length; }
float loadFactor() { return loadFactor; }
}
--------------------------------------------HashMap源码 end--------------------------------------
③、自我实现HashMap
《====================HashMap源码解析总结==============================
HashMap总结:
①、HashMap 采用链表数组的方式存储一个个的Entry(key-value、next、hash值[对key的hashcode进行hash算法]),实现了快速查询、插入、删除功能。
②、put、get之前先对key进行hash算法,并且得到的hash值。进行 hash&length-1 相当于hash%(数组length)取模,得到index。
详见:public V put(K key, V value) 、 public V get(Object key) 方法
③、当put时,hash碰撞时,key相同或key对象相同,把table[i]上的entry的e.value 赋给V oldValue,value赋给e.value, return oldValue值。这样新的key-value与原来的key-value通过链表结构的方式连接。
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
④、hash算法和indexFor(int h, int length) 【Returns index for hash code h.】
==================================================================》
未完……………………待续