1、什么是HashMap呢?
基于哈希表的 Map 接口的實現(xiàn)。此實現(xiàn)提供所有可選的映射操作,并允許使用 null 值和 null 鍵。(除了非同步和允許使用 null 之外,HashMap 類與 Hashtable 大致相同。)此類不保證映射的順序,特別是它不保證該順序恒久不變。 此實現(xiàn)假定哈希函數(shù)將元素適當(dāng)?shù)胤植荚诟魍爸g,可為基本操作(get 和 put)提供穩(wěn)定的性能。迭代 collection 視圖所需的時間與 HashMap 實例的“容量”(桶的數(shù)量)及其大小(鍵-值映射關(guān)系數(shù))成比例。所以,如果迭代性能很重要,則不要將初始容量設(shè)置得太高(或?qū)⒓虞d因子設(shè)置得太低)。
干脆說吧,HashMap就是一個數(shù)組+單鏈表+紅黑樹的組合,在其組合中可以實現(xiàn)數(shù)據(jù)存儲、更新、刪除與訪問。
2、搞懂HashMap的數(shù)據(jù)結(jié)構(gòu)。
我為何要說HashMap是個數(shù)組+鏈表+紅黑樹的組合?那是因為高效,至于為何這樣設(shè)計,這樣設(shè)計高效在哪?我慢慢講解。
一個可擴(kuò)容數(shù)組,多個哈希單鏈表,多個紅黑樹,三者組成了HashMap的數(shù)據(jù)結(jié)構(gòu)。
那么假設(shè)現(xiàn)在我們向HashMap添加數(shù)據(jù) S ,一定是要知道以下幾件事的。
- 要知道存在數(shù)組那個位置,即怎么存?所以出現(xiàn)了hash生成位置(也是為了均勻的存入數(shù)組中,減少空間浪費)。
- 位置知道了,那么數(shù)組空間夠嗎?就需要進(jìn)行判斷,不夠(不夠是多少,看下節(jié))則擴(kuò)容。
- 現(xiàn)在數(shù)組空間夠了,那么數(shù)據(jù) S 存入數(shù)組,當(dāng)然此過程可能會出現(xiàn)hashcode沖突,即該數(shù)組中對應(yīng)位置已經(jīng)存有值。
- 此時建立對應(yīng)數(shù)組某位置的單鏈表,將 S 鏈接在單鏈表末尾。
- S填到對應(yīng)位置就完了嗎?當(dāng)然不是,當(dāng)單鏈表長度大于某值時,將會轉(zhuǎn)換為紅黑樹,其實簡單的說是為了查找方便,另外當(dāng)紅黑樹頂點樹小于某值,又會恢復(fù)為單鏈表,至此整個添加過程才會結(jié)束。
好了,添加知道了,那么刪除、更新會不同嗎?答案是相同的,只要了解了Hashmap的運作機(jī)制,其實過程是大同小異的。
3 Hashmap的擴(kuò)容機(jī)制。
跟著權(quán)威 -> 源碼,一步步講解擴(kuò)容是怎么擴(kuò)的。
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 默認(rèn)Hashmap數(shù)組起始容量16
static final int MAXIMUM_CAPACITY = 1 << 30;//最大容量
static final float DEFAULT_LOAD_FACTOR = 0.75f;//擴(kuò)容臨界點比例,即達(dá)到數(shù)組的0.75容量則擴(kuò)容
static final int TREEIFY_THRESHOLD = 8;//樹化闕值,即最小可樹化值
static final int UNTREEIFY_THRESHOLD = 6;//鏈表化闕值,即最大可鏈表化值
static final int MIN_TREEIFY_CAPACITY = 64;//Hashmap數(shù)組容量大于64并且達(dá)到樹化闕值,允許樹化,否則擴(kuò)容
Node(int hash, K key, V value, Node<K,V> next) {//數(shù)組節(jié)點
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {//鏈表結(jié)點
TreeNode<K,V> parent; // red-black tree links
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev; // needed to unlink next upon deletion
boolean red;
TreeNode(int hash, K key, V val, Node<K,V> next) {
super(hash, key, val, next);
}
名稱 | 作用 |
---|---|
DEFAULT_INITIAL_CAPACITY | 默認(rèn)Hashmap數(shù)組起始容量 |
MAXIMUM_CAPACITY | Hashmap數(shù)組最大容量 |
DEFAULT_LOAD_FACTOR | 達(dá)到數(shù)組的0.75容量則擴(kuò)容 |
TREEIFY_THRESHOLD | 樹化闕值,即最小可樹化值 |
UNTREEIFY_THRESHOLD | 鏈表化闕值,即最大可鏈表化值 |
MIN_TREEIFY_CAPACITY | Hashmap數(shù)組容量大于64并且達(dá)到樹化闕值,允許樹化,否則擴(kuò)容 |
hashmap做節(jié)點相關(guān)操作時都會毋庸置疑的調(diào)取resize方法,因為resize是對目前數(shù)組長度及鏈表轉(zhuǎn)換進(jìn)行重置的必要源碼,在resize中首先檢查一下目前的數(shù)組長度oldCap,如果大于MAXIMUM_CAPACITY 最大值,那不添加,如果小于最大值,將oldcap擴(kuò)大2倍(左移一位)在比對MAXIMUM_CAPACITY ,可以則保存......,必要代碼以附屬至下方。
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;
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;
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;
}
4、HashMap既高深又簡單的算法?
方法 | 作用 |
---|---|
void clear() | 從此映射中移除所有映射關(guān)系。 |
Object clone() | 返回此 HashMap 實例的淺表副本:并不復(fù)制鍵和值本身。 |
boolean containsKey(Object key) | 如果此映射包含對于指定鍵的映射關(guān)系,則返回 true。 |
boolean containsValue(Object value) | 如果此映射將一個或多個鍵映射到指定值,則返回 true。 |
Set<Map.Entry<K,V>> entrySet() | 返回此映射所包含的映射關(guān)系的 Set 視圖。 |
V get(Object key) | 返回指定鍵所映射的值;如果對于該鍵來說,此映射不包含任何映射關(guān)系,則返回 null。 |
boolean isEmpty() | 如果此映射不包含鍵-值映射關(guān)系,則返回 true。 |
Set<K> keySet() | 返回此映射中所包含的鍵的 Set 視圖。 |
V put(K key, V value) | 在此映射中關(guān)聯(lián)指定值與指定鍵。 |
void putAll(Map<? extends K,? extends V> m) | 將指定映射的所有映射關(guān)系復(fù)制到此映射中,這些映射關(guān)系將替換此映射目前針對指定映射中所有鍵的所有映射關(guān)系。 |
V remove(Object key) | 從此映射中移除指定鍵的映射關(guān)系(如果存在)。 |
int size() | 返回此映射中的鍵-值映射關(guān)系數(shù)。 |
Collection<V> values() | 返回此映射所包含的值的 Collection 視圖。 |
常用方法使用
import java.util.HashMap;
public class hashmap {
public static void main(String[] args) {
@SuppressWarnings("unused")
HashMap<Integer, String> hashmap = new HashMap<Integer ,String>();
hashmap.put(01, "張三");
hashmap.put(02, "李四");
hashmap.put(03, "王二");
hashmap.put(04, "趙六");
System.out.println("長度:"+hashmap.size());
System.out.println(hashmap.get(02));
hashmap.remove(02);
System.out.println(hashmap.get(02));
}
}
put定位
//舒適化hashmap
@SuppressWarnings("unused")
HashMap<Integer, String> hashmap = new HashMap<Integer ,String>();
hashmap.put(01, "張三");
//源碼自上而下定位
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
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;
}
get定位
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) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
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;
}
remove定位
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
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;
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;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p)
tab[index] = node.next;
else
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}