兜兜轉轉開發java有些時間,可是每次都是用到採取學習,用過又回到原點,反反覆覆,究其緣由還是沒有合理的整理總結,只是個不斷重複搬磚、運磚的中高級工種,沒有不可替代的核心競爭力。
why?因爲你30min——1h能完成的東西,不熟悉的人多花點時間也是可以完成的,這樣你的核心價值競爭力充其量等於兩者的時間差而已。
前段時間和某某大神聊起這個事情,他的原話(學習源碼,知其然,知其所以然是核心競爭力)給我很有啓發。
那怎樣學習源碼?方法很重要!!!
學習源碼最有效的方式還是3部曲。
①、猜測(基於對其有些瞭解的情況下,只要工作或學習中用的多了就有大致的認識了)
②、驗證/求證(逐步閱讀、或debug源碼細節)
③、自我實現其功能(這是一個昇華的步驟)
==========================================================================
一、HashMap源碼分析
1、猜測 (HashMap 既有數組的快速查找有點 + 快速增刪功能)
假如自己實現這個設計你會怎樣設計呢?
(數組+鏈表結構【鏈表增加、刪除只要改變next、pre指向的對象就可以實現】)、那樣就用鏈表存儲元素,用數組存 儲指向鏈表的引用。
這樣通過數組的index就可以定位到鏈表的位置,這使用了數組快速查詢的功能;定位到了鏈表的位置,通過hash算法得到鏈表中的元素位置,可快速的定位到具體的元素(換言之,'HashMap'實質就是一個“鏈表數組”)。
那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.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<K,V>[]) 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.】
==================================================================》
未完……………………待續