菜鸟一个,大佬勿喷!!!
HashMap设计概要
HashMap采用分组的方式存储键值对(Map),分组的依据是Hash,每组是一个链表或红黑树。 键值对被封装为Node对象。Node类的成员变量如下
final int hash;//key的hash值
final K key;
V value;
Node<K,V> next;//形成链表
HashMap 变量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
static final int MAXIMUM_CAPACITY = 1 << 30;
static final float DEFAULT_LOAD_FACTOR = 0.75f;
static final int TREEIFY_THRESHOLD = 8;
static final int UNTREEIFY_THRESHOLD = 6;
static final int MIN_TREEIFY_CAPACITY = 64;
transient Node<K,V>[] table;
transient Node<K,V>[] table;//存储键值对的node数组
transient Set<Map.Entry<K,V>> entrySet;//
transient int size;//存储键值对的总量
transient int modCount;//HashMap对象修改次数
int threshold;//链表转化为红黑树的阈值
final float loadFactor;//负载因子,当size>teble.length*loadFactor时,table扩容
秘制Hash()
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
数据插入
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;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;//teble为空则扩容
if ((p = tab[i = (n - 1) & hash]) == null)
//n为table数组的长度,且n为2的n次幂,n-1用二进制表示为1(符号位)加一串零加一串1
//比如n=4,n-1的二进制为100...0011
//将n表示为2的a次方,则(n-1)&hash则为取hash后a位表示的数值,切该数为数组下标
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;
}