HashMap原始碼解析、ConcurrentHashMap、ConcurrentSkipListMap 初步熟悉 (JDK1.7之一)
兜兜轉轉開發java有些時間,可是每次都是用到採取學習,用過又回到原點,反反覆覆,究其緣由還是沒有合理的整理總結,只是個不斷重複搬磚、運磚的中高階工種,沒有不可替代的核心競爭力。
why?因為你30min——1h能完成的東西,不熟悉的人多花點時間也是可以完成的,這樣你的核心價值競爭力充其量等於兩者的時間差而已。
前段時間和某某大神聊起這個事情,他的原話(學習原始碼,知其然,知其所以然是核心競爭力)給我很有啟發。
那怎樣學習原始碼?方法很重要!!!
學習原始碼最有效的方式還是3部曲。
①、猜測(基於對其有些瞭解的情況下,只要工作或學習中用的多了就有大致的認識了)
②、驗證/求證(逐步閱讀、或debug原始碼細節)
③、自我實現其功能(這是一個昇華的步驟)
==========================================================================
一、HashMap原始碼分析
1、猜測 (HashMap 既有陣列的快速查詢有點 + 快速增刪功能)
假如自己實現這個設計你會怎樣設計呢?
(陣列+連結串列結構【連結串列增加、刪除只要改變next、pre指向的物件就可以實現】)、那樣就用連結串列儲存元素,用陣列存 儲指向連結串列的引用。
這樣通過陣列的index就可以定位到連結串列的位置,這使用了陣列快速查詢的功能;定位到了連結串列的位置,通過hash演算法得到連結串列中的元素位置,可快速的定位到具體的元素(換言之,'
那HashMap中最關鍵的方法有 put 、get方法,那具體實現怎麼做的,詳見HashMap原始碼。
2、HashMap原始碼如下:
--------------------------------------------HashMap原始碼 start--------------------------------------
package java.util;import java.io.*;
public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, 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
/**
* The load factor used when none specified in constructor.
*/
//-----> 預設載入因子 0.75f(陣列length >= 16*0.75=12(陣列的閾值)時,HashMap就需要擴容)
//預設負載因子,當容器使用率達到這個75%的時候就擴容
/**
* An empty table instance to share when the table is not inflated.
*/
//-----> EMPTY_TABLE 定義一個空集合
//當陣列表還沒擴容的時候,一個共享的空表物件
/**
* The table, resized as necessary. Length MUST Always be a power of two.
*/
//不可以序列化的 table,預設是一個空陣列
//內部陣列表,用來裝entry,大小隻能是2的n次方。
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
/**
* The number of key-value mappings contained in this map.
*/
// 陣列的size 是陣列的length
//儲存的鍵值對的個數
/**
* 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時(空陣列),則該值作為初始化內部陣列的初始容量
*/
/**
* The load factor for the hash table.
*
* @serial
*/
//由建構函式傳入的指定負載因子
/**
* 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的修改次數
/**
* 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.
* <p/>
* 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的最大值
/**
* holds values which can't be initialized until after VM is booted.
*/
/**
* 靜態內部類,提供一些靜態常量
*/
/**
* Table capacity above which to switch to use alternative hashing.
*/
/**
* 容量閾值,初始化hashSeed的時候會用到該值
*/
static {
//獲取系統變數jdk.map.althashing.threshold
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
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
/**
* Constructs an empty <tt>HashMap</tt> 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
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
//初始容量不能大於預設的最大容量
initialCapacity = MAXIMUM_CAPACITY;
//負載因子不能小於0,且不能為“NaN”(NaN(“不是一個數字(Not a Number)”的縮寫))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
//將傳入的負載因子賦值給屬性
this.loadFactor = loadFactor;
//此時並不會建立容器,因為沒有 傳具體值
// 沒下次擴容大小
/**
* 此時並不會建立容器,因為沒有傳具體值。
* 當下次傳具體值的時候,才會“根據這次的初始容量”,建立一個內部陣列。
* 所以此次的初始容量只是作為下一次擴容(新建)的容量。
*/
threshold = initialCapacity;
//該方法只在LinkedHashMap中有實現,主要在建構函式初始化和clone、readObject中有呼叫。
}
/**
* Constructs an empty <tt>HashMap</tt> 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) {
//生成空陣列,並指定擴容值
}
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
/**
* 生成一個空hashmap,初始容量和負載因子全部使用預設值。
*/
public HashMap() {
//生成空陣列,並指定擴容值,預設this(16,0.75);
}
/**
* Constructs a new <tt>HashMap</tt> with the same mappings as the
* specified <tt>Map</tt>. The <tt>HashMap</tt> is created with
* default load factor (0.75) and an initial capacity sufficient to
* hold the mappings in the specified <tt>Map</tt>.
*
* @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) {
//生成空陣列,並指定擴容值
DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
//由於此時陣列為空,所以使用“擴容臨界值”新建一個數組
//將傳入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 新陣列容量
*/
// Find a power of 2 >= toSize
//內部陣列的大小必須是2的n次方,所以要找到“大於”toSize的“最小的2的n次方”。
//下次擴容臨界值
threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
table = new Entry[capacity];
//根據陣列長度初始化hashseed
}
// 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中有呼叫。
*/
}
/**
* Initialize the hashing mask value. We defer initialization until we
* really need it.
*/
/**
* 根據內部陣列長度初始化hashseed
* @param capacity 內部陣列長度
* @return hashSeed是否初始化
*/
boolean currentAltHashing = hashSeed != 0;
boolean useAltHashing = sun.misc.VM.isBooted() &&
(capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
boolean switching = currentAltHashing ^ useAltHashing;
//為true則賦初始化值
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值
*/
int h = hashSeed;
//如果key是字串型別,就使用stringHash32來生成hash值
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).
//二次雜湊
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 下標
*/
// assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
//除模取餘,相當於hash % length,&速度更快
}
/**
* 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 <tt>true</tt> if this map contains no key-value mappings.
*
* @return <tt>true</tt> if this map contains no key-value mappings
*/
/**
* 判斷hashmap是否為空
* @return true為空,false為非空
*/
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.
*
* <p>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.)
*
* <p>A return value of {@code null} does not <i>necessarily</i>
* 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
return getForNullKey();
//如果key不為null,則先根據key,找到其entry
//返回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
*/
if (size == 0) {
return null;
}
//查詢table[0]處的連結串列,如果找到entry的key為null,就返回其value
if (e.key == null)
return e.value;
}
return null;
}
/**
* Returns <tt>true</tt> if this map contains a mapping for the
* specified key.
*
* @param key The key whose presence in this map is to be tested
* @return <tt>true</tt> if this map contains a mapping for the specified
* key.
*/
/**
* 判斷指定key是否存在
* @param key 鍵值名
* @return 存在則返回true
*/
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節點
*/
if (size == 0) {
return null;
}
//如果key為null,則其hash值為0,否則計算hash值
int hash = (key == null) ? 0 : hash(key);
//根據hash值找到table下標,然後迭代該下標中的連結串列裡的每一個entry節點
e != null;
e = e.next) {
Object k;
//如果找到該節點則返回該節點
((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 <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
/**
* 存入一個鍵值對,如果key重複,則更新value
* @param key 鍵值名
* @param value 鍵值
* @return 如果存的是新key則返回null,如果覆蓋了舊鍵值對,則返回舊value
*/
public V put(K key, V value) {
//如果陣列為空,則新建陣列
inflateTable(threshold);
}
//如果key為null,則把value放在table[0]中
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,則繼續執行下一條指令,將此鍵值對存入連結串列頭
*/
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
}
/**
* 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<K,V> e = table[0]; e != null; e = e.next) {
//如果找到key為null的entry,則覆蓋其value,並返回舊value
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
//操作次數加一
modCount++;
//檢視是否需要擴容,然後將entry插入table的指定下標中的連結串列頭中
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
/**
* 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,則繼續執行下一條指令,將此鍵值對存入連結串列頭
*/
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 新陣列容量
*/
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
//如果當前陣列容量已經達到最大值了,則將擴容的臨界值設定為Integer.MAX_VALUE(Integer.MAX_VALUE是容量的臨界點)
threshold = Integer.MAX_VALUE;
return;
}
//建立一個擴容後的新陣列
Entry[] newTable = new Entry[newCapacity];
//將當前陣列中的鍵值對存入新陣列
transfer(newTable, initHashSeedAsNeeded(newCapacity));
//用新陣列替換舊陣列
table = newTable;
//計算下一個擴容臨界點
}
/**
* 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<K,V> e : table) {
//查詢連結串列裡的每一個entry
Entry<K,V> 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
}
}
}
/**
* 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) {
//傳入陣列的鍵值對數
if (numKeysToBeAdded == 0)
return;
//如果本地陣列為空,則新建本地陣列
if (table == EMPTY_TABLE) {
//從當前擴容臨界值和傳入陣列的容量中選擇大的一方作為初始陣列容量
}
/*
* 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);
//不能大於最大容量
targetCapacity = MAXIMUM_CAPACITY;
//當前陣列長度
int newCapacity = table.length;
//從當前陣列長度開始增加,每次增加一個“2次方”,直到大於所需容量為止
newCapacity <<= 1;
//如果發現內部陣列長度需要增加,則擴容內部陣列
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 <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
/**
* 根據key刪除entry節點
* @param key 被刪除的entry的key值
* @return 被刪除的節點的value,刪除失敗則返回null
*/
Entry<K,V> 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
*/
if (size == 0) {
return null;
}
//計算key的hash值
int hash = (key == null) ? 0 : hash(key);
//計算所屬下標
int i = indexFor(hash, table.length);
//找到下標所儲存的單鏈表的頭節點
Entry<K,V> e = prev;
//迭代單鏈表找到要刪除的節點
while (e != null) {
Entry<K,V> 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,刪除成功
*/
if (size == 0 || !(o instanceof Map.Entry))
return null;
Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
Object key = entry.getKey();
int hash = (key == null) ? 0 : hash(key);
//得到陣列索引
Entry<K,V> prev = table[i];
Entry<K,V> e = prev;
//開始遍歷該單鏈表
while (e != null) {
Entry<K,V> next = e.next;
//找到節點
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中的所有元素
*/
modCount++;
//將table中的每一個元素都設定成null
size = 0;
}
/**
* Returns <tt>true</tt> 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 <tt>true</tt> 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的鍵值對
return containsNullValue();
Entry[] tab = table;
//遍歷table,找遍每條連結串列
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
*/
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 <tt>HashMap</tt> 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
*/
HashMap<K,V> result = null;
try {
result = (HashMap<K,V>)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<K,V>
* hashmap中每一個鍵值對都是存在Entry物件中,entry還儲存了自己的hash值等資訊
* Entry被儲存在hashmap的內部陣列中。
* @param <K> 鍵值名key
* @param <V> 鍵值value
*/
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;//key
V value;//key-value對應的值
//陣列中每一項(連結串列)可能儲存多個entry(key-value鍵值對、hash(key)、next),而這些entry就是以連結串列的形式被儲存,此next指向下一個entry
int hash;//hash值
/**
* Creates new entry.
*/
//初始化節點
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
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中實現了這個方法
}
/**
* This method is invoked whenever the entry is
* removed from the table.
*/
//每移除一個entry就被呼叫一次,在HashMap的子類LinkedHashMap中實現了這個方法;
}
}
/**
* 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;
//重新計算儲存位置
}
//將鍵值對與他的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 key 鍵值名
* @param value 鍵值
* @param bucketIndex 被插入的下標
*/
void createEntry(int hash, K key, V value, int bucketIndex) {
// 儲存“bucketIndex”位置的Entry<K,V>值到“e”(Entry類中的next)中
Entry<K,V> e = table[bucketIndex];
// ***設定“bucketIndex”位置的元素為“新Entry”,
// ***設定“e”為“新Entry的下一個節點”
size++;
}
/**
* 所有迭代器的抽象父類
* @param <E> 儲存的資料的型別
*/
private abstract class HashIterator<E> implements Iterator<E> {
//指向下一個節點
int expectedModCount; // For fast-fail // 用於判斷快速失敗行為
int index; // current slot //當前table下標
Entry<K,V> 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<K,V> nextEntry() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
Entry<K,V> 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<V> {
public V next() {
return nextEntry().value;
}
}
//KeyIterator迭代器
private final class KeyIterator extends HashIterator<K> {
public K next() {
return nextEntry().getKey();
}
}
//KeyIterator迭代器
private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {
public Map.Entry<K,V> next() {
return nextEntry();
}
}
// Subclass overrides these to alter behavior of views' iterator() method
// 返回各種迭代器物件
return new KeyIterator();
}
Iterator<V> newValueIterator() {
return new ValueIterator();
}
Iterator<Map.Entry<K,V>> newEntryIterator() {
return new EntryIterator();
}
// Views
//含有所有entry節點的一個set集合
private transient Set<Map.Entry<K,V>> 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 <tt>remove</tt> operation), the results of
* the iteration are undefined. The set supports element removal,
* which removes the corresponding mapping from the map, via the
* <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
* <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
* operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
* operations.
*/
/**
* 返回一個set集合,裡面裝的都是hashmap的value。
* 因為map中的key不能重複,set集合中的值也不能重複,所以可以裝入set。
*
* 在hashmap的父類AbstractMap中,定義了Set<K> keySet = null;
* 如果keySet為null,則返回內部類KeySet。
* @return 含有所有key的set集合
*/
Set<K> ks = keySet;
return (ks != null ? ks : (keySet = new KeySet()));
}
/**
* 內部類,生成一個set集合,裡面裝有此hashmap的所有key。
*/
private final class KeySet extends AbstractSet<K> {
public Iterator<K> 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 <tt>remove</tt> operation),
* the results of the iteration are undefined. The collection
* supports element removal, which removes the corresponding
* mapping from the map, via the <tt>Iterator.remove</tt>,
* <tt>Collection.remove</tt>, <tt>removeAll</tt>,
* <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
* support the <tt>add</tt> or <tt>addAll</tt> operations.
*/
/**
* 返回一個Collection集合,裡面裝的都是hashmap的value。
* 因為map中的value可以重複,所以裝入Collection。
*
* 在hashmap的父類AbstractMap中,定義了Collection<V> values = null;
* 如果values為null,則返回內部類Values。
*/
Collection<V> vs = values;
return (vs != null ? vs : (values = new Values()));
}
/**
* 內部類,生成一個Collection集合,裡面裝有此hashmap的所有value
*/
private final class Values extends AbstractCollection<V> {
public Iterator<V> 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 <tt>remove</tt> operation, or through the
* <tt>setValue</tt> 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 <tt>Iterator.remove</tt>,
* <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
* <tt>clear</tt> operations. It does not support the
* <tt>add</tt> or <tt>addAll</tt> operations.
*
* @return a set view of the mappings contained in this map
*/
/**
* 返回一個set集合,裡面裝的是所有的entry結點
* (相當於把map集合轉化成set集合)
* @return 含有所有entry的set集合
*/
return entrySet0();
}
/**
* 如果entrySet為null,則返回一個含有所有entry節點的一個set集合
* @return 含有所有entry節點的一個set集合
*/
private Set<Map.Entry<K,V>> entrySet0() {
Set<Map.Entry<K,V>> es = entrySet;
return es != null ? es : (entrySet = new EntrySet());
}
/**
* 內部類,含有所有entry節點的一個set集合
*/
private final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
//返回迭代器
return newEntryIterator();
}
//查詢傳入entry是否存在
if (!(o instanceof Map.Entry))
return false;
Map.Entry<K,V> e = (Map.Entry<K,V>) o;
Entry<K,V> candidate = getEntry(e.getKey());
return candidate != null && candidate.equals(e);
}
//刪除
return removeMapping(o) != null;
}
//返回鍵值對數
return size;
}
//清空
HashMap.this.clear();
}
}
/**
* Save the state of the <tt>HashMap</tt> instance to a stream (i.e.,
* serialize it).
*
* @serialData The <i>capacity</i> of the HashMap (the length of the
* bucket array) is emitted (int), followed by the
* <i>size</i> (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<K,V> 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