定義
HashMap 是一個(gè)鍵值對(duì)的集合癞松,key值允許為null辟躏,key值不允許重復(fù)。value可重復(fù)涤躲,可null报嵌。
源碼分析
- 內(nèi)部屬性
//初始大小
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
//最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
//負(fù)載因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//從鏈表變?yōu)榧t黑樹(shù)的鏈表個(gè)數(shù)
static final int TREEIFY_THRESHOLD = 8;
//從鏈表變?yōu)榧t黑樹(shù)數(shù)組最小的容量
static final int MIN_TREEIFY_CAPACITY = 64;
//hashMap中的實(shí)際存放元素的屬性虱咧,同時(shí)也是個(gè)單向鏈表
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
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; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
//Node數(shù)組,存放元素的數(shù)組
transient Node<K,V>[] table;
//map的大小
transient int size;
//擴(kuò)容的臨界值
int threshold;
//負(fù)載因子
final float loadFactor;
- 構(gòu)造器
HashMap 提供了4個(gè)無(wú)參構(gòu)造器沪蓬。其實(shí)值得一看的 只有一個(gè)彤钟。
如果看重效率,則可以設(shè)置負(fù)載因子低一點(diǎn)跷叉,hash碰撞概率低
如果看重內(nèi)存逸雹,則可以設(shè)置負(fù)載因子高一點(diǎn)。
當(dāng)熱云挟,也看情況吧梆砸,想詳細(xì)了解,看下邊的put方法的代碼园欣。
public HashMap(int initialCapacity, float loadFactor) {
//判斷初始大小是否合法
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
//判斷負(fù)載因子是否合法
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
//該方法為了讓所有的初始大小都為2的N次方帖世,
//也就是說(shuō) 當(dāng)你使用Map map = new HashMap(10,0.75f);
//他的容量并不是10 而是16 沸枯,就是因?yàn)檎{(diào)用了下邊這個(gè)方法日矫。
//容量為2的N次方可以讓hash值更加分散。減少hash碰撞
this.threshold = tableSizeFor(initialCapacity);
}
/**
* Returns a power of two size for the given target capacity.
*/
static final int tableSizeFor(int cap) {
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;
}
- 擴(kuò)容
final Node<K,V>[] resize() {
//老的table
Node<K,V>[] oldTab = table;
//老table容量
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//老table臨界值
int oldThr = threshold;
//新table的容量绑榴,臨界值
int newCap, newThr = 0;
//非首次擴(kuò)容 并且 創(chuàng)建HashMap時(shí)沒(méi)有指定大小
if (oldCap > 0) {
//如果老的table已經(jīng)擴(kuò)到最大哪轿,則返回原來(lái)的table
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//在判斷中就擴(kuò)容了兩倍,如果新的容量小于最大值并且老的容量大于等于16 則新的臨界值也增加2倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
//這種情況是翔怎,在構(gòu)造器已經(jīng)指定HashMap的大小
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
//首次擴(kuò)容窃诉,使用默認(rèn)的容量和臨界值
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
//如果新的臨界值為0.則設(shè)置
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
//創(chuàng)建擴(kuò)容后的Node數(shù)組
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
//如果oldTal中有數(shù)據(jù),則遷移到newTab中
if (oldTab != null) {
//循環(huán)判斷遷移
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
//如果該位置上沒(méi)有鏈表赤套,則直接放入
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
//如果該位置放置的是紅黑樹(shù)飘痛,//TODO(分組遷移?)
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
//如果該位置放置的是鏈表
//這一步其實(shí)可以這么理解容握,擴(kuò)容后宣脉,數(shù)組下標(biāo)也會(huì)發(fā)生變化。相當(dāng)于是把鏈表分散
//下邊 借了個(gè)圖 幫助理解
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
//不需要重新計(jì)算hash剔氏,只需要看看原來(lái)的hash值新增的那個(gè)bit是1還是0就好了
//是0的話索引沒(méi)變脖旱,是1的話索引變成“原索引+oldCap”
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;
}
微信圖片_20180205170215.png
- 添加 put(k,v)
/**
* 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>.)
*/
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) {
//tab :table數(shù)組堪遂。p: 鏈表的第一個(gè)位置的元素。n:總?cè)萘棵惹臁:索引位置
Node<K,V>[] tab; Node<K,V> p; int n, i;
//首次添加,擴(kuò)容
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//當(dāng)前索引位置上沒(méi)有元素币旧,直接放入該位置践险。
//在找位置的時(shí)候 hash & (n-1) 這個(gè)算法也是很厲害的。在1.7的時(shí)候還是hash % n計(jì)算得出索引位置吹菱。
//該算法效率更高巍虫。 hash & (n-1) = hash % n
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
//該位置已經(jīng)有元素了。
Node<K,V> e; K k;
//如果該位置的元素hashcode值相等并且通過(guò)equals也相等鳍刷,則直接覆蓋占遥。
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//如果該元素為紅黑樹(shù),則直接按紅黑樹(shù)處理输瓜。(在鏈表上超過(guò)8個(gè)則為紅黑樹(shù))
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//在該位置的元素下判斷并且以鏈表的方式放入瓦胎。
for (int binCount = 0; ; ++binCount) {
//如果該鏈表下一個(gè)為空,則把這個(gè)鏈下去
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//如果該鏈表已經(jīng)有8個(gè)了尤揣。則變?yōu)榧t黑樹(shù)搔啊。
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
//在這里,值得一提的是北戏,如果此時(shí)鏈表數(shù)量達(dá)到了8负芋,但是容量沒(méi)有達(dá)到64
//則先擴(kuò)容再說(shuō),不變成二叉樹(shù)
//關(guān)于紅黑樹(shù)(增加插入嗜愈,查找的效率)旧蛾,等有時(shí)間了(徹底研究明白)在開(kāi)篇文章。
treeifyBin(tab, hash);
break;
}
//此時(shí)蠕嫁,如果新添加的和該鏈表上的有相同的 則直接覆蓋锨天,跳出循環(huán),
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
//把新的元素變?yōu)橄乱粋€(gè)元素拌阴,繼續(xù)循環(huán)判斷
p = e;
}
}
//上邊老說(shuō)覆蓋绍绘,其實(shí)這里是覆蓋的代碼。
//就是如果重復(fù)了迟赃。則把值賦給e
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
//下邊在借個(gè)圖陪拘,關(guān)于擴(kuò)容的流程.圖來(lái)源(美團(tuán)技術(shù)沙龍)
hashMap put方法執(zhí)行流程圖.png
- value get(key) 通過(guò)鍵值或者value值。 //如果看懂了put的流程纤壁,那么get是很容易理解的左刽。
/**
* 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)
*/
public V get(Object key) {
Node<K,V> e;
//直接跳轉(zhuǎn)到getNode(hash,key)方法
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;
//先做一下Node數(shù)組的非空判斷,
//并且酌媒,通過(guò)hash & (n-1)獲取索引位置賦值給first
//在這里欠痴,first就是該位置上鏈表的第一個(gè)元素迄靠。
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//如果第一個(gè)元素通過(guò)hash和equals判斷都相等,則直接返回
//之所以第一步就這么判斷喇辽,是為了效率掌挚。
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
//如果該位置是以鏈表存在
if ((e = first.next) != null) {
//如果是紅黑樹(shù),則從紅黑樹(shù)中查詢
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
//不是紅黑樹(shù)菩咨,從鏈表中查詢吠式,一直next直到 hash和equals都相等。
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
- remove(key) 刪除方法
/**
* 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>.)
*/
public V remove(Object key) {
Node<K,V> e;
//跳轉(zhuǎn)removeNode方法抽米。
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
/**
* Implements Map.remove and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to match if matchValue, else ignored
* @param matchValue if true only remove if value is equal
* @param movable if false do not move other nodes while removing
* @return the node, or null if none
*/
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;特占、
//非空判斷并且賦值
//p為該位置的第一個(gè)元素
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
//定義node變量,也就是一會(huì)要?jiǎng)h除的變量
//接下來(lái)的邏輯是找到node
//經(jīng)過(guò)判斷 該值就是node
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
//如果第一個(gè)不是云茸,就從該鏈表繼續(xù)往下找
else if ((e = p.next) != null) {
//如果是紅黑樹(shù)是目,則通過(guò)getTreeNode從紅黑樹(shù)中查詢
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
//不是紅黑樹(shù),一直next找到node
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
//找到node后标捺,因?yàn)閙atchValue為false懊纳。則肯定會(huì)進(jìn)入判斷
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
//如果是紅黑樹(shù),則從紅黑樹(shù)中刪除
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
//如果node==p 那么把該位置設(shè)置成node的下一個(gè)宜岛,如果是空长踊,則為空
else if (node == p)
tab[index] = node.next;
//如果不是,則從新設(shè)置next關(guān)系
//剛開(kāi)始看著個(gè)的時(shí)候有點(diǎn)懵萍倡。但是后來(lái)發(fā)現(xiàn)了身弊。
//如果能進(jìn)到下邊這個(gè)判斷,則p就不是第一個(gè)元素了列敲, 而是node的上一個(gè)元素阱佛,
//因?yàn)樵谏线呇h(huán)的時(shí)候 有這么一行代碼 p = e;
else
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
- 總的來(lái)說(shuō) JDK1.8 無(wú)論是從找索引的位置,還是擴(kuò)容的機(jī)制戴而,還是鏈表變紅黑樹(shù)都增加了效率凑术。
1.8很不錯(cuò)。