【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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章