JAVA8java
1.HashMap.put 方法实现了Map.put(K key,V value)的方法。直接调用内部方法node
大体思路是这样的:数组
下面是putVal方法解析app
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空间-默认size=16 n = (tab = resize()).length; if ((p = tab[i = (n - 1) & hash]) == null) // 算出新node在table中的位置,若对应位置为null,新建一个node并放入对应位置. // 注意: (n - 1) & hash 求余操做 等价于 hash%n(只有n为2的幂时才成立,见下图) tab[i] = newNode(hash, key, value, null); else { //在table对应位置有node时 Node<K,V> e; K k; if (p.hash == hash && // key同样 (hash值相同,且key 同样,相同实例或者知足Object.equals方法) ((k = p.key) == key || (key != null && key.equals(k)))) // 不知足此条件则发生hash碰撞 e = p; else if (p instanceof TreeNode) // hash碰撞的状况下,用链表解决,链表大于8时,改成红黑树. 当node为treeNode时,putTreeVal->红黑树 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { //hash for (int binCount = 0; ; ++binCount) { //用for循环将链表指针后移,将新node在链表加在尾部 if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); if (binCount >= TREEIFY_THRESHOLD - 1) // 当链表长度大于8时,转成红黑树 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) //当node中旧的值null或者onlyIfAbsent==false时,将新的value替换原来的value. e.value = value; afterNodeAccess(e); //新node塞入table后作的作的事情,在HashMap中是一个空方法(LinkedHashMap中有有使用, move node to last) return oldValue; } } ++modCount; if (++size > threshold) //新的size大于阈值(默认0.75*table.length)时,扩容. resize(); afterNodeInsertion(evict); return null; }
总结.this
1.第一次put操做时,才为table分配内存空间,指针
2.当发生hash碰撞时,先链表,链表长度大于8时,转为红黑树.code