源码来源:JDK1.8
本文仅讲解put方法主要的处理流程,加深对hashmap的理解。直接上码。
public HashMap() {this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted}
hashMap无参构造器,只初始化负载因子,不初始化大小
//put方法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)//1.1、数据为空,初始化table数组n = (tab = resize()).length;if ((p = tab[i = (n - 1) & hash]) == null)//2.1、当前数组下标位置没有数据,将数据插入数组tab[i] = newNode(hash, key, value, null);else {//2.2、当前数据下标位置已存在数据Node<K,V> e; K k;if (p.hash == hash &&((k = p.key) == key || (key != null && key.equals(k))))//2.2.1、 hash值相同 and key值相同将数据替换e = p;else if (p instanceof TreeNode)// 2.2.2、树结构,遍历树找到相同的key,将旧节点赋给e用于下面value值的覆盖。未找到相同的key则插入树返回null,方法内部不做过多讲述,有兴趣可自行研究。e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);else {//2.2.3、如果不是树结构(链表),遍历整个链表for (int binCount = 0; ; ++binCount) {if ((e = p.next) == null) {//2.2.3.1、链接末尾未找到key相同数据,插入链表(尾插法)p.next = newNode(hash, key, value, null);//插入后判断链表长度 >= 7,转成红黑树结构。 -1 是因为头部数组位也算一位实际链表长度8位//treeifyBin方法中当tab数组长度 < 64时执行链表转红黑树操作,否则只进行扩容操作if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1sttreeifyBin(tab, hash);break;}//2.2.3.2、链表中存在key相同的数据,替换数据if (e.hash == hash &&((k = e.key) == key || (key != null && key.equals(k))))break;p = e;}}//2.2.4、链表中存在与当前插入数据的相同的keyif (e != null) { // existing mapping for keyV oldValue = e.value;//2.2.4.1、onlyIfAbsent 为false 或者oldValue为空 替换value值if (!onlyIfAbsent || oldValue == null)e.value = value;//2.2.4.2、linkedHashMap用到 hashmap本地实现为空,linkedHashMap使用父类hashmap的put方法,重写了以下方法。afterNodeAccess(e);//2.2.4.3、返回旧value方法结束(不涉及到扩容)return oldValue;}}++modCount;//3.1、新插入节点后,判断是否满足扩容条件 threshold = capacity * load factor(负载因子 0.75)if (++size > threshold)resize();//linkedHashMap用到 hashmap本地实现为空,linkedHashMap使用父类hashmap的put方法,重写了以下方法。afterNodeInsertion(evict);return null;}