1、HashMap的使用方法:
HashMap<Object, Object> hashMap = new HashMap<>();
hashMap.put("Cat", 1);
hashMap.put("Dog", 2);
2、HashMap的put的存储原理及冲突处理:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
int h;
//h >>> 16 无符号右移16位 ,得到的实际上是int的高16位
//key != null,取key的hashCode异或自己的高16位
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)//如果table为空,初始化table的长度。DEFAULT_INITIAL_CAPACITY = 1 << 4;
n = (tab = resize()).length;
(1)if ((p = tab[i = (n - 1) & hash]) == null)//假设第一次put,16-1&hash。得到一个在16范围内的i.
//如果tab[i] != null.实际上hash冲突可能产生
tab[i] = newNode(hash, key, value, null);
else {//hash冲突后的处理
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)//如果table[i]已经是一个树了,说明table[i]已经不是第一次处理hash冲突了。
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {//是table[i]处理hash冲突,还没有形成红黑树
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {//到达链表尾部--没找到key相同的
//(1)的位置已经将tab[i]赋值给了链表p.现tab[i]冲突,只需要将put的键值对挂在链表的下个位置即可。
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st TREEIFY_THRESHOLD = 8
treeifyBin(tab, hash);//java 8之后引入的如果链表的长度达到TREEIFY_THRESHOLD ,则将链接转成树结构。
//红黑树的引入
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
//如果在table[i]的遍历过程中发现hash,和key都是相同的,则直接覆盖即可。---更新操作
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;
}