1、初始化

HashMap map= new HashMap(16);

初始值
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;

2、put方法

public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); //扰动函数
    }

hashmap实际上就是数组+链表的散列结构,通过传入的key的hashcode通过一次扰动函数与数组容量取余,得到其下标,(为什么要用扰动函数:首先,一般的hashmap的长度是小于16位的,而key的hashcode值是int类型,为32位,若直接用hashcode与容量取余,则在低16位不变,高16位变化的情况下,其数组下边均一致,容易hash冲突,故将其高16位也纳入计算中,有效降低冲突概率)

no talk show code: 插入hashmap方法

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //数组为空或容量为空,则扩容,默认扩容为16,阈值为12
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //未出现hash碰撞,直接放入数组其下标对应位置
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        //hash碰撞,采用链表法就是将相同hash值的对象组织成一个链表放在hash值对应的槽位
        else {
            Node<K,V> e; K k;
            //传入的key与链表的头节点相同,直接覆盖
            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) {
                    //将新节点放入其尾部,若碰撞的节点个数大于等于8,调用树化方法
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //传入的key与链表的某个节点相同,直接覆盖
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            //传入的key已存在,用传入的value覆盖原value,并返回原value
            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;
    }

3、resize方法

final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
		//旧表已有容量
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
			//扩容,容量与阈值均乘2
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
		//初始化也是为比传入的容量值大的最小的2的整数倍,如传15则初始容量为16
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
		//未传入初始值,则取默认值,容量为16,阈值为12
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
		//若新表容量大于int最大值或者新表容量*负载因子大于int最大值,容量取int最大值
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
					//将原节点引用置为空
                    oldTab[j] = null;
					//当前节点非链表节点,直接与新表容量取余得到新表下标,将原节点放入新表此下标即可
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
					//若是红黑树(待完善))
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
					//链表结构
                    else { // preserve order
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
						//用碰撞节点的hash值同旧表容量做与(&)操作,可将原一个链表分成2个链表插入新数组中
						//例如3,11,19,27,35,43与旧表容量为8取余均为3,但同8做与(&)操作,结果为0,8,0,8,0,8
						//即可将3,19,35放入新表newTab[3]的位置,将11,27,43,放入新表newTab[11]的位置
                        do {
                            next = e.next;
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

4、treeifyBin方法

final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
		//虽然链表节点大于8,但是tab的长度小于64,先扩容
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();
		//树化
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            TreeNode<K,V> hd = null, tl = null;
			//将所有链表节点转为树节点,并确定其上下关系prev、next
            do {
                TreeNode<K,V> p = replacementTreeNode(e, null);
                if (tl == null)
                    hd = p;
                else {
                    p.prev = tl;
                    tl.next = p;
                }
                tl = p;
            } while ((e = e.next) != null);
			//真正转红黑树的方法(待完善))
            if ((tab[index] = hd) != null)
                hd.treeify(tab);
        }
    }

5、treeify方法

   final void treeify(Node<K,V>[] tab) {
            TreeNode<K,V> root = null;
            for (TreeNode<K,V> x = this, next; x != null; x = next) {
                next = (TreeNode<K,V>)x.next;
                x.left = x.right = null;
				//上一个方法确定了上下游的树节点关系,这里将第一个节点置为根节点
                if (root == null) {
                    x.parent = null;
                    x.red = false;
                    root = x;
                }
                else {
                    K k = x.key;
                    int h = x.hash;
                    Class<?> kc = null;
					//根据每个节点的hash值依次放到当前叶子节点为空的节点的左或右节点上
					//hash大的放入右节点,小的放入左节点,生成一个简单的树
                    for (TreeNode<K,V> p = root;;) {
                        int dir, ph;
                        K pk = p.key;
                        if ((ph = p.hash) > h)
                            dir = -1;
                        else if (ph < h)
                            dir = 1;
                        else if ((kc == null &&
                                  (kc = comparableClassFor(k)) == null) ||
                                 (dir = compareComparables(kc, k, pk)) == 0)
                            dir = tieBreakOrder(k, pk);

                        TreeNode<K,V> xp = p;
                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
                            x.parent = xp;
                            if (dir <= 0)
                                xp.left = x;
                            else
                                xp.right = x;
							//将树转为红黑树(待完善)
                            root = balanceInsertion(root, x);
                            break;
                        }
                    }
                }
            }
			//保证数组的第一个节点为根节点
            moveRootToFront(tab, root);
        }
03-28 04:40