public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
/**
*默認(rèn)初始化的數(shù)組容量 必須是2的冪次方
* The default initial capacity - MUST be a power of two.
*/
//在獲取數(shù)組下標(biāo)的時(shí)候tab[(n - 1) & hash] 要做到& 與運(yùn)算的結(jié)果等于取模的效果,必須n是2的冪次方行贪,
//[n-1] 即1111**的形式才能保證 結(jié)果取決于hash值骆捧,才能做到更好的散列霉晕。 假如數(shù)組有0的話,0 & 操作后還是0 就一定會(huì)限制散列的范圍
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* 最大的數(shù)組容量
* 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.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* 默認(rèn)的計(jì)算擴(kuò)容的加載因子 正勒, 超出了負(fù)載因子與當(dāng)前容量的乘積時(shí),擴(kuò)大原先的2容量
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* 鏈表轉(zhuǎn)樹(shù)的判斷條件
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* 樹(shù)轉(zhuǎn)鏈表的判定條件
* The bin count threshold for untreeifying a (split) bin during a
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* 默認(rèn)的 HashMap被使用的空間大小超過(guò)這個(gè)常量時(shí),會(huì)開(kāi)始樹(shù)化
*/
static final int MIN_TREEIFY_CAPACITY = 64;
/**
*鏈表的節(jié)點(diǎn)
* Basic hash bin node, used for most entries. (See below for
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
*/
static class Node<K,V> implements Map.Entry<K,V> {
final int hash; //哈希值
final K key; //key
V value; // value
Node<K,V> next;//鏈表下個(gè)節(jié)點(diǎn)
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
//每個(gè)節(jié)點(diǎn)的hash值扶关, 是將key的hashcode 和 value的hashcode 做 ^ 操作得到
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
//設(shè)置新值 返回舊值
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
/* ---------------- Static utilities -------------- */
/**
*/
//沒(méi)有直接使用key的hashcode(),將鍵的hashcode的高16位異或低16位(高位運(yùn)算)数冬,
//這樣即使數(shù)組table的length比較小的時(shí)候节槐,
//也能保證高低位都參與到Hash的計(jì)算中
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
/**
* 返回最近的不小于輸入?yún)?shù)的2的整數(shù)次冪
* Returns a power of two size for the given target capacity.
*/
static final int tableSizeFor(int cap) {
//再賦值給n的目的是令找到的目標(biāo)值大于或等于原值
//如果原值就是2的冪次方,不進(jìn)行減一 通過(guò)如下計(jì)算 會(huì)擴(kuò)大一倍拐纱。
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n +
1;
}
/* ---------------- Fields -------------- */
/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
*/
//hash表
transient Node<K,V>[] table;
/**
* Holds cached entrySet(). Note that AbstractMap fields are used
* for keySet() and values().
*/
transient Set<Map.Entry<K,V>> entrySet;
/**
* The number of key-value mappings contained in this map.
*/
//當(dāng)前hashMap的大小
transient int size;
/**
* 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).
*/
transient int modCount;
/**
* The next size value at which to resize (capacity * load factor).
*
* @serial
*/
// (The javadoc description is true upon serialization.
// Additionally, if the table array has not been allocated, this
// field holds the initial array capacity, or zero signifying
// DEFAULT_INITIAL_CAPACITY.)
//threshold其實(shí)就表示了hashmap的真實(shí)容量大小
int threshold;
/**
* The load factor for the hash table.
*hash table的負(fù)載因子
* @serial
*/
final float loadFactor;
/* ---------------- Public operations -------------- */
/**
* 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
*/
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
/**
* 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.
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
/**
* 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
*/
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
/**
* Implements Map.putAll and Map constructor
*
* @param m the map
* @param evict false when initially constructing this map, else
* true (relayed to method afterNodeInsertion).
*
*/
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
//未初始化
if (table == null) { // pre-size
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
//tableSizeFor 返回最近的不小于輸入?yún)?shù)的2的整數(shù)次冪
threshold = tableSizeFor(t);
}
//已經(jīng)初始化了铜异, 傳入的元素實(shí)際個(gè)數(shù)大于當(dāng)前設(shè)定的數(shù)組大小, 則擴(kuò)容
else if (s > threshold)
resize();
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
putVal(hash(key), key, value, false, evict);
}
}
}
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
* @see #put(Object, Object)
*/
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
/**
* Implements Map.get and related methods
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//數(shù)組不為null秸架,數(shù)組長(zhǎng)度要大于零揍庄,之后根據(jù)key或渠道數(shù)組元素Node不為零。
// (n - 1) & hash 因n是為2的冪东抹,(n - 1) & hash就是獲取數(shù)組的某個(gè)下標(biāo)蚂子。
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//先檢查第一個(gè)元素是否否滿(mǎn)足條件
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
//是紅黑紅 則調(diào)用對(duì)應(yīng)的查找方法
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key); //樹(shù)中找
// 鏈表 循環(huán)直到找到下一個(gè)滿(mǎn)足條件的
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null); //鏈表中找
}
}
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.
*/
public boolean containsKey(Object key) {
return getNode(hash(key), key) != 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.
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//tab 未初始化或者長(zhǎng)度為0沃测,進(jìn)行擴(kuò)容 table 被延遲到插入新數(shù)據(jù)時(shí)再進(jìn)行初始化
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)// (n - 1) & hash 確定元素存放在哪個(gè)桶中,桶中不包含該節(jié)點(diǎn)的引用食茎,新生成結(jié)點(diǎn)放入桶中
tab[i] = newNode(hash, key, value, null);
else {
//數(shù)組當(dāng)前位置有值了
Node<K,V> e; K k;
//如果存在相同的值蒂破, 就是鏈表一個(gè)值的hash和key相等, e指向該值
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 如果桶中的引用類(lèi)型為 TreeNode别渔,則調(diào)用紅黑樹(shù)的插入方法
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//// 對(duì)鏈表進(jìn)行遍歷附迷,并統(tǒng)計(jì)鏈表長(zhǎng)度
for (int binCount = 0; ; ++binCount) {
// 鏈表中不包含要插入的鍵值對(duì)節(jié)點(diǎn)時(shí),則將該節(jié)點(diǎn)接在鏈表的最后
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//樹(shù)化操作
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//包含要插入的key值钠糊,break終止遍歷
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//e 表示是否存在要插入的鍵值
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
//鍵值對(duì)數(shù)量超過(guò)閥值 進(jìn)行擴(kuò)容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* @return the table
*/
//擴(kuò)容之后挟秤,要重新計(jì)算鍵值對(duì)的位置,并把它們移動(dòng)到合適的位置上去
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
//tab已經(jīng)初始化過(guò)了
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
//有參數(shù)initialCapacity構(gòu)造方法 初始化時(shí) 使用 threshold 變量暫時(shí)保存 initialCapacity 參數(shù)的值
newCap = oldThr;
else {
//無(wú)參數(shù)夠著方法
// zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)
MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
// 創(chuàng)建新的桶數(shù)組抄伍,桶數(shù)組的初始化也是在這里完成的
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
//重新計(jì)算鍵值對(duì)的位置
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
//e.hash & (newCap - 1) 新位置在要們?cè)谥暗臄?shù)組位置艘刚,要么在(之前的數(shù)組大小+之前的位置)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
// // 重新映射時(shí),需要對(duì)紅黑樹(shù)進(jìn)行拆分
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
// 遍歷鏈表截珍,并將鏈表節(jié)點(diǎn)按原順序進(jìn)行分組
//(e.hash & oldCap) == 0 在老數(shù)組的位置
//(e.hash & oldCap) == 1 在(老數(shù)組的位置 + oldcap大信噬酢)
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
}
HashMap重要源碼解讀
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
- 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)纸颜,“玉大人兽泣,你說(shuō)我怎么就攤上這事⌒菜铮” “怎么了唠倦?”我有些...
- 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)涮较。 經(jīng)常有香客問(wèn)我稠鼻,道長(zhǎng),這世上最難降的妖魔是什么狂票? 我笑而不...
- 正文 為了忘掉前任枷餐,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘毛肋。我一直安慰自己怨咪,他們只是感情好,可當(dāng)我...
- 文/花漫 我一把揭開(kāi)白布润匙。 她就那樣靜靜地躺著诗眨,像睡著了一般。 火紅的嫁衣襯著肌膚如雪孕讳。 梳的紋絲不亂的頭發(fā)上匠楚,一...
- 那天,我揣著相機(jī)與錄音厂财,去河邊找鬼芋簿。 笑死,一個(gè)胖子當(dāng)著我的面吹牛璃饱,可吹牛的內(nèi)容都是我干的与斤。 我是一名探鬼主播,決...
- 文/蒼蘭香墨 我猛地睜開(kāi)眼荚恶,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼撩穿!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起谒撼,我...
- 序言:老撾萬(wàn)榮一對(duì)情侶失蹤食寡,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后廓潜,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體抵皱,經(jīng)...
- 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
- 正文 我和宋清朗相戀三年辩蛋,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了呻畸。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
- 正文 年R本政府宣布剑鞍,位于F島的核電站昨凡,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏蚁署。R本人自食惡果不足惜便脊,卻給世界環(huán)境...
- 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望光戈。 院中可真熱鬧哪痰,春花似錦遂赠、人聲如沸。這莊子的主人今日做“春日...
- 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至肋演,卻和暖如春抑诸,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背爹殊。 一陣腳步聲響...
- 正文 我出身青樓层玲,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親绒瘦。 傳聞我的和親對(duì)象是個(gè)殘疾皇子称簿,可洞房花燭夜當(dāng)晚...
推薦閱讀更多精彩內(nèi)容
- Map是java中用于存儲(chǔ)建值對(duì)的一種數(shù)據(jù)結(jié)構(gòu)方式.鍵不能重復(fù), 每一個(gè)鍵可以匹配多個(gè)值(也就是一個(gè)鏈表).這個(gè)接...
- 注意:Java1.7和Java1.8中的HashMap實(shí)現(xiàn)有較大改動(dòng) Java1.7 HashMap 標(biāo)記接口Cl...
- 一.HashMap的由來(lái): 1.array是數(shù)組的數(shù)據(jù)結(jié)構(gòu),對(duì)于隨機(jī)訪問(wèn)get和set是優(yōu)勢(shì)惰帽,對(duì)于新增和刪除是劣勢(shì)...
- 前幾天在一個(gè)網(wǎng)站上回答問(wèn)題憨降,雖然是平時(shí)經(jīng)常遇到的,但有很多點(diǎn)都被人模糊掉或者用一些專(zhuān)業(yè)名詞蓋掉该酗。筆者覺(jué)得這個(gè)問(wèn)題很...
- 今天老師講了關(guān)于Python語(yǔ)言和底層C語(yǔ)言之間的關(guān)系授药,Python更具兼容性,可以很好的兼容所錄入的各種資源庫(kù)呜魄,...