【java】【13】HashMap

1.jdk1.8的結構

數組 + 鏈表 + 紅黑樹

2.鏈表

Node
hash
key
value
nextNode

3.數組

Node[] table

4.數組的長度是2的n次方

1.任何數和2的n次方-1做與運算都小於等於在2的n次方-1
剛好用來做hash計算數組的位子

2.任何數和2的n次方做與運算,只有兩種結果0或者2的n次方
這個可以在resize的時候確定節點是高位和地位

5.put操作

如果hash出來的數組沒有值,新建一個Node
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);

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;
	if ((tab = table) == null || (n = tab.length) == 0)
	    //如果數組爲空,先初始化
		n = (tab = resize()).length;
	if ((p = tab[i = (n - 1) & hash]) == null)
	    //如果hash出來的數組沒有值,新建一個Node
		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))))
			//如果hash、key相等 值相等就替換
			e = p;
		else if (p instanceof TreeNode)
		    //如果是p是個樹
			e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
		else {
			for (int binCount = 0; ; ++binCount) {
			    //死循環訪問鏈表,直到最後一個節點(p.next)
				if ((e = p.next) == null) {
					p.next = newNode(hash, key, value, null);
					if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
					    //如果鏈表的長度大於 8-1,需要轉成紅黑樹
						treeifyBin(tab, hash);
					break;
				}
				//如果鏈表中存在和key相等的元素跳出循環
				if (e.hash == hash &&
					((k = e.key) == key || (key != null && key.equals(k))))
					break;
				p = e;
			}
		}
		if (e != null) { // existing mapping for key
		    //有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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章