基于數(shù)組的ArrayList長于按索引獲取對應元素溉潭,而在中間位置插入和刪除元素,都涉及了對數(shù)組整體的移動少欺、復制等操作喳瓣,相比于鏈表的插入刪除來說代價比較大≡薇穑基于鏈表的LinkedList長于隨機插入刪除畏陕,Java的雙向鏈表(LinekdList)只能從頭到尾或者從尾到頭遍歷鏈表獲取元素,相較于ArrayList也是比較慢的仿滔。那么有沒有一種折中的解決方案惠毁,使得插入刪除和取元素都比較便捷呢?我認為HashMap可以算是這么一種折中的解決方案堤撵。
HashMap概述
HashMap是一個實現(xiàn)了Map接口的哈希表仁讨,允許使用null值和null鍵。除了非同步和允許使用null之外实昨,HashMap類與Hashtable大致相同洞豁。HashMap不保證映射的順序,不保證該順序恒久不變荒给。
HashMap不是線程安全的丈挟,如果想要使用線程安全的HashMap,可以通以下代碼來得到:
Map map = Collections.synchronizedMap(new HashMap());
源碼實現(xiàn)
HashMap在實現(xiàn)上采用了類似“鏈表的數(shù)組”這種數(shù)據(jù)結(jié)構(gòu)志电,也有將之稱為“拉鏈法”的曙咽,實現(xiàn)方式如圖。
當HashMap根據(jù)key計算的hash值一樣時挑辆,就發(fā)生了碰撞例朱,這時就會根據(jù)如圖所示的結(jié)構(gòu)存儲存儲對應的對象孝情。而這種碰撞發(fā)生非常多的話,那么HashMap讀取對象的速度就會變慢洒嗤。在java 8之后箫荡,如果一個“桶”的記錄過大(TREEIFY_THRESHOLD = 8),HashMap會動態(tài)的使用一個專門的treemap實現(xiàn)來替換它渔隶。這樣可以降低頻繁發(fā)生碰撞時讀對象的時間復雜度羔挡,當然,這需要你插入的key實現(xiàn)了Comparable接口间唉,否則這樣的優(yōu)化是你享受不到的~
// 單向鏈表的數(shù)據(jù)結(jié)構(gòu)
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
// 下個節(jié)點的引用
Node<K,V> next;
// 在構(gòu)造函數(shù)中初始化
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;
}
// 復寫equal方法
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;
}
}
重要的屬性:
/**
* 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.)
*/
// 存儲元素的實體數(shù)組
transient Node<K,V>[] table;
/**
* The number of key-value mappings contained in this map.
*/
// map的容量
transient int size;
/**
* 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 = 容量 * 加載因子
int threshold;
/**
* The load factor for the hash table.
*
* @serial
*/
// 哈希表的加載因子,加載因子在這種實現(xiàn)方式中是數(shù)組被填充的程度呈野,哈希表
// 填充的越滿低矮,發(fā)生沖突的機會越大。在Java的實現(xiàn)中默認的加載因子是0.75
final float loadFactor;
接下來看一下HashMap默認的無參構(gòu)造函數(shù)际跪,看一下HashMap是如何初始化的:
/**
* 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
}
根據(jù)注釋來看說是用默認的初始化容量(16)和默認的加載因子(0.75)來構(gòu)造一個空的哈希Map商佛。雖然注釋是這么說的,但是并沒有看到其他的動作姆打,特別是上面提到的table這個數(shù)組良姆,在構(gòu)造函數(shù)中沒有初始化的動作,其實他是在插入元素的時候才真正的初始化這個數(shù)組幔戏。來看一下我們平時調(diào)用的map.put(key,value)是如何實現(xiàn)的:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
具體的實現(xiàn)是putVal玛追,那么看下這個方法:
/**
* 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;
// 如果table為空
if ((tab = table) == null || (n = tab.length) == 0)
// 事實上調(diào)用了resize(),初始化的動作就是在resize方法中完成的
n = (tab = resize()).length;
// 這里根據(jù)哈希計算數(shù)組下標還是有點玄機的闲延,留待之后討論
// 這里如果數(shù)組對應的索引下還沒有插入值痊剖,將值插入
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {// 如果已經(jīng)有值了,即發(fā)生了沖突
Node<K,V> e; K k;
// 如果鍵值相同
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// HashMap如果頻繁的發(fā)生碰撞垒玲,那么速度就會變慢陆馁,在java8 之后
// 如果同一個索引頻繁的發(fā)生碰撞,那么就會將這個索引底下的鏈表
// 轉(zhuǎn)換為紅黑樹合愈,提升搜索的速度叮贩。很好,很牛逼的改進佛析!
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
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;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
以上簡單的看了下HashMap是如何插入一個值的,在計算索引上寸莫,HashMap并沒有采用我們平時的哈希值對數(shù)組長度取余捺萌。而是采用了效率比較高的 & 運算,h & (length - 1)膘茎,在注釋中也說了桃纯,哈希表的長度必須是2的次冪酷誓,這么做的好處是什么呢?首先是h & (length - 1)慈参,length是2的次冪呛牲,那么length - 1用二進制表示的話必定全是1,而采用&運算的話驮配,無論是0或1和1進行&運算,其結(jié)果既可能是0着茸,也可能是1壮锻,這樣就保證了運算后的均勻性。
在以上的注釋中也提到了對table的初始化是在resize方法中完成的涮阔,那么看看resize方法:
/**
* 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
*/
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
// 原數(shù)組不空
if (oldCap > 0) {
// 如果oldCap已經(jīng)為最大容量
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 每次擴容是之前的2倍猜绣,一直是2的次冪
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
// 重新創(chuàng)建table數(shù)組,原數(shù)組為空敬特,oldThr不為空
// 擴展為oldThr大小
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
// 原數(shù)組為空掰邢,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;
// 桶中只有一個元素
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
// 如果第一個節(jié)點是TreeNode
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;
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;
}
接下來再看一下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;
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;
// hash & (length - 1)得到紅黑樹的樹根或者是鏈表頭
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
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)// 紅黑樹
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);
}
}
return null;
}
淺析暫時就到這了伟阔。