“在介紹HashMap之前,爲了方便更清楚地理解源碼,先大致說說HashMap的實現原理,
HashMap 是基於數組 + 鏈表實現的, 首先HashMap就是一個大數組,在這個數組中,通過hash值去尋對應位置的元素, 如果遇到多個元素的hash值一樣,那麼怎麼保存,這就引入了鏈表,在同一個hash的位置,保存多個元素(通過鏈表關聯起來)。HashMap 所實現的基於<key, value>的鍵值對形式,是由其內部內Entry實現。”
Entry,是一個靜態類,實現Map.Entry< K ,V>,通過他可以構成一個單向鏈表,只是一個內部類。
HashMap類繼承了AbstractMap父類,實現Map,Cloneable, Serializble接口。
public class HashMAp<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
- serialVersionUID叫序列化ID 先擺着:
java對象序列化的意思就是將對象的狀態轉化成字節流,以後可以通過這些值再生成相同狀態的對象。對象序列化是對象持久化的一種實現方法,它是將對象的屬性和方法轉化爲一種序列化的形式用於存儲和傳輸。反序列化就是根據這些保存的信息重建對象的過程。
序列化:將java對象轉化爲字節序列的過程。
反序列化:將字節序列轉化爲java對象的過程。 - 負載因子:
會影響HashMap性能
首先回憶HashMap的數據結構,- 我們都知道有序數組存儲數據,對數據的索引效率都很高,但是插入和刪除就會有性能瓶頸(回憶ArrayList)
- 鏈表存儲數據,要一次比較元素來檢索出數據,所以索引效率低,但是插入和刪除效率高(回憶LinkedList),
兩者取長補短就產生了哈希散列這種存儲方式,也就是HashMap的存儲邏輯.
而負載因子表示一個散列表的空間的使用程度,有這樣一個公式:initailCapacity*loadFactor=HashMap的容量。
所以負載因子越大則散列表的裝填程度越高,也就是能容納更多的元素,元素多了,鏈表大了,所以此時索引效率就會降低。
反之,負載因子越小則鏈表中的數據量就越稀疏,此時會對空間造成浪費,但是此時索引效率高。
官方操作一波0.75f,咱也不知道爲啥哈哈哈,效率高唄。
JDK1.8 開始HashMap的實現是 數組+鏈表+紅黑樹
//序列化ID
private static final long serialVersionUID = 362498820763181265L;
// 初始容量16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//最大容量2^30
static final int MAXIMUM_CAPACITY = 1 << 30;
//默認負載因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//當鏈表達到8時轉化爲紅黑樹
static final int TREEIFY_THRESHOLD = 8;
//當紅黑樹節點數小於6時,轉化爲鏈表
static final int UNTREEIFY_THRESHOLD = 6;
/**
* 這個字段決定了當hash表的至少大小爲多少時,鏈表才能進行樹化。這個設計時合理的,
* 因爲當hash表的大小很小時,這時候表所需的空間還不多,可以犧牲空間減少時間,所以這個情況下
* 當存儲的節點過多時,最好的辦法是調整表的大小,使其增大,而不是將鏈表樹化。
*/
static final int MIN_TREEIFY_CAPACITY = 64;
下面介紹鍵值在HashMap中的存儲形式。
static class Node<K,V> implements Map.Entry<K,V> {
final int hash; //hash的value
final K key; //key
V value; //value 的 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;
}
//Entry的get方法、toString方法
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
計算hashCode中key和value異或值,將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;
}
判斷地址值,判斷o是否爲Map.Entry的實例,判斷類型和鍵值。
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;
}
hash(Object key)
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
先獲取到key的hashCode,然後進行移位再進行異或運算,複雜操作原因爲了減少hash衝突。
“ 如果惡意程序知道我們用的是Hash算法,則在純鏈表情況下,它能夠發送大量請求導致哈希碰撞,然後不停訪問這些key導致HashMap忙於進行線性查找,最終陷入癱瘓,即形成了拒絕服務攻擊(DoS)。
關於Java 8中的hash函數,原理和Java 7中基本類似。Java 8中這一步做了優化,只做一次16位右位移異或混合,而不是四次,但原理是不變的。”
comparableClassFor(Object x)
static Class<?> comparableClassFor(Object x) {
if (x instanceof Comparable) {
Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
if ((c = x.getClass()) == String.class) // bypass checks
return c;
if ((ts = c.getGenericInterfaces()) != null) {
for (int i = 0; i < ts.length; ++i) {
if (((t = ts[i]) instanceof ParameterizedType) &&
((p = (ParameterizedType)t).getRawType() ==
Comparable.class) &&
(as = p.getActualTypeArguments()) != null &&
as.length == 1 && as[0] == c) // type arg is c
return c;
}
}
}
return null;
}
comparableClassFor(Object x)方法,當x的類型爲X,且X直接實現了Comparable接口(比較類型必須爲X類本身)時,返回x的運行時類型;否則返回null。
compareComparables(Class<?> kc, Object k, Object x)
@SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
static int compareComparables(Class<?> kc, Object k, Object x) {
return (x == null || x.getClass() != kc ? 0 :
((Comparable)k).compareTo(x));
}
如果x的類型爲kc,則返回k.compareTo(x),否則返回0.
tableSizeFor(int cap)
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1; // 將n和n右移1位的值進行或運算,將結果賦值給n
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
返回大於等於cap的最小的二次冪數值。
/**
存儲鍵值對的數組,一般是2的冪
* 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.)
* 存儲鍵值對的數組,一般是2的冪
*/
transient Node<K,V>[] table;
/**
* Holds cached entrySet(). Note that AbstractMap fields are used
* for keySet() and values().
* 鍵值對緩存,它們的映射關係集合保存在entrySet中。
* 即使Key在外部修改導致hashCode變化,緩存中還可以找到映射關係
*/
transient Set<Map.Entry<K,V>> entrySet;
/**
* The number of key-value mappings contained in this map.
* 鍵值對的實際個數
*/
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).
* 記錄HashMap被修改結構的次數。
* 修改包括改變鍵值對的個數或者修改內部結構,比如rehash
* 這個域被用作HashMap的迭代器的fail-fast機制中
* (參考ConcurrentModificationException)
*/
transient int modCount;
/**
* The next size value at which to resize (capacity * load factor).
* 擴容的臨界值,通過capacity * load factor可以計算出來。超過這個值HashMap將進行擴容
* @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.)
int threshold;
/**
* The load factor for the hash table.
*負載因子
* @serial
*/
final float loadFactor;
public HashMap(int initialCapacity, float loadFactor)
/**
* 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
*/
/**
* 使用指定的初始化容量initial capacity 和負載因子load factor構造一個空HashMap
*
* @param initialCapacity 初始化容量
* @param loadFactor 負載因子
* @throws IllegalArgumentException 如果指定的初始化容量爲負數或者加載因子爲非正數。
*/
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);
}
如果初始化容量小於零,非法參數異常,大於最大容量,更新最大容量,判斷負載因子異常。
public HashMap(int 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.
*/
/**
* 使用指定的初始化容量initial capacity和默認負載因子DEFAULT_LOAD_FACTOR(0.75)構造一個空HashMap
*
* @param initialCapacity 初始化容量
* @throws IllegalArgumentException 如果指定的初始化容量爲負數
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap()
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
/**
* 使用指定的初始化容量(16)和默認負載因子DEFAULT_LOAD_FACTOR(0.75)構造一個空HashMap
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
public HashMap(Map<? extends K, ? extends V> m)
/**
* 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
* *使用與
*指定的<tt>map.<tt>創建“hashmap”時
*默認荷載係數(0.75)和初始承載力足以
*將映射保存在指定的<tt>映射中。
*
*@param m要將其映射放置在此映射中的映射
*@如果指定的映射爲空,則引發NullPointerException
*/
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
整個夜,瘋狂揮霍。
final void final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) (Map<? extends K, ? extends V> m, boolean evict)
//將一個map即m放入當前實例的table中
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
//如果table沒初始化,ft = 一個值
//t = ft 與 最大mum容量比較 賦值
//t > 閾值條件,賦值改變threshold
if (tablet == null) { // pre-size
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
threshold = tableSizeFor(t);
}
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);
}
}
}
啊mdzz… 搞來搞去就是一頓操作改了threshold的值爲tableSizeFor((map大小 / loadFactor) + 1.0F)
public int size()
/**
* Returns the number of key-value mappings in this map.
*
* @return the number of key-value mappings in this map
*/
/**
*返回此映射中的鍵值映射數
*@返回此映射中的鍵值映射數
*/
public int size() {
return size;
}
public boolean isEmpty()
/**
* Returns <tt>true</tt> if this map contains no key-value mappings.
*
* @return <tt>true</tt> if this map contains no key-value mappings
*/
/**
*如果此映射不包含鍵值映射,則返回<tt>true。
*@如果此映射不包含鍵值映射,則返回<tt>true
*/
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.
*
* <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)
*/
/**
*返回指定鍵映射到的值,
*或者@code NULL如果此映射不包含鍵的映射。
*<p>更正式地說,如果此映射包含來自鍵的映射
*@code k到值@code v這樣@code(key==null?K==空:
*key.equals(k)),則此方法返回@code v,否則返回
*返回@code空。(最多可以有一個這樣的映射。)
*<p>返回值@code null不一定<i>
*指示映射不包含鍵的映射;它還
*可能映射顯式地將鍵映射到@code null。
*@link containskey containskey操作可用於
*區分這兩種情況。
* @see #put(Object, Object)
*/
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key)
/**
* Implements Map.get and related methods.
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
/**
* 根據key的哈希值和key獲取對應的節點
*
* @param hash 指定參數key的哈希值
* @param key 指定參數key
* @return 返回node,如果沒有則返回null
*/
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//表不爲空、長度不爲零且key對應value不空
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//如果桶中的第一個節點得哈希值就和指定參數hash對應
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
//返回第一個節點
//如果沒匹配上
if ((e = first.next) != null) {
//第一節點屬於樹的實例
if (first instanceof TreeNode)
//當前桶用紅黑樹,調用紅黑樹get方法獲取節點
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
//若爲空,返回null
return null;
}
根據key的哈希值獲取key對應節點。
public boolean containsKey(Object key)
// 調用getNode方法來獲取鍵值對,如果沒有找到返回false,找到了就返回ture
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
- public V put(K key, V value)
- final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict)
- final Node<K,V>[] resize()
put方法首先檢查HashMap是否爲空,爲空執行resize初始化map,若非空,計算tab數組下標[(n - 1) & hash],判斷數組對象是否爲空,爲空時新建一個node節點。
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//檢查hashmap是否爲空,爲空的話執行resize,相當於初始化一個map
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//非空時,計算tab數組下標[(n - 1) & hash],判斷數組對象是否爲空,爲空時新建一個node節點。
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
//數組對象非空,tab[i]非空,
//判斷該節點的key與即將put的key值是否相同,相同的話先講tab[i]對應的node存儲起來。
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//判斷tab[i]是否爲紅黑樹對象,若tab節點爲紅黑樹,則執行一次樹對象put操作。
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//處理tab[i]節點爲鏈表對象,通過一個計數器binCount統計鏈表長度。如果tab[i]對象p的next爲null,則鏈表到頭了,這個時候新建一個node<key,value>節點爲p.next。
//如果鏈表長度計數器binCount>7即TREEIFY_THRESHOLD - 1即8-1,即鏈表長度大於8時,則進行紅黑樹轉換。如果不滿足轉換條件,鏈表種插入新節點完畢,無需其他操作
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
//針對存在相同key的節點,執行value覆蓋,並返回舊值。
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
//若tab大小超過閾值(容量*負載因子),執行resize擴容操作,返回null。
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
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
newCap = oldThr;
else { // 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"})
// 新建擴容數組
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
// 遍歷老數組
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
// 老數組子節點爲null,通過e.hash & (newCap - 1)獲取數組下標,將節點填充到該數組對象中
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
// 節點爲紅黑色時
((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 {
next = e.next;
// 元素位置沒有發生變化
// 原hash與原容量進行與運算,loHead、loTail位置不變時的頭尾節點
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
// 元素位置發生變化
// hiHead、hiTail位置變化後新的頭節點和尾節點
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
// 位置不變時,(e.hash & oldCap) == 0,數組當前下標指向loHead
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
// 位置變化時,數組下標變爲[j + oldCap],指向頭節點
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
final void treeifyBin(Node<K,V>[] tab, int hash)樹化
/**
* Replaces all linked nodes in bin at index for given hash unless
* table is too small, in which case resizes instead.
*/
/**
* Replaces all linked nodes in bin at index for given hash unless
* table is too small, in which case resizes instead.
*/
/**
*替換給定哈希的索引處bin中的所有鏈接節點,除非
*表太小,在這種情況下會調整大小。
*/
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
//如果元素數組長度爲空或者小於MIN_TREEIFY_CAPACITY,執行resize操作
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
//數組長度與hash值位運算,得到鏈表的首節點,hd是樹首節點,tl是樹尾結點
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
//節點變成樹節點
TreeNode<K,V> p = replacementTreeNode(e, null);
//如果尾結點爲空,賦值給首節點,樹的根結點
//如果尾結點不爲空,則是雙向鏈表結構構成
if (tl == null)
hd = p;
else {
//prev指向前一個節點尾結點
p.prev = tl;
//next指向當前節點
tl.next = p;
}
//把當前節點設置爲尾結點
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
//轉換成紅黑樹
}
}
public void putAll(Map<? extends K, ? extends V> m)
/**
* 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
*/
public void putAll(Map<? extends K, ? extends V> m) {
//調用putMapEntries
putMapEntries(m, true);
}