android HashMap源码添加数据的全过程解析(一)

        String name="zhang";
        Log.e(TAG, "initView name: "+name.hashCode() );
        HashMap<String, String> params = new HashMap<>();
        params.put(name,"");

这里的name,打印的值是:115864556

    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);
    }

这里,我们求一下hash(Object key)返回的值是多少,即:

key.hashcode() =115864556

在hash(Object key)方法中,key是不等于null,所以return:115864556 ^ (115864556 >>> 16)

115864556 ^ (115864556 >>> 16) 是10进制,我们换算成2进制

即:

110111001111111001111101100 ^ (110111001111111001111101100 >>> 16)

>>> 表示正向右移,就是如果是负数右移,那它的结果就是正的,

110111001111111001111101100右移16位,从右往左数16下,靠右边的数,都去掉,即:11011100111,高位没有数了,我们补上0,即:000000000000000011011100111

所以:

110111001111111001111101100 ^ (110111001111111001111101100 >>> 16)

= 110111001111111001111101100 ^ 000000000000000011011100111

异或运算是2者相同则为0,不同则为1

110111001111111001111101100

000000000000000011011100111

它们之间隔的太密,加个小空格好看好算,即:

11 011 100 111 111 1001 111 101 100

00 000 000 000 000 0011 011 100 111

11 011 100 111 111 1010 100 001 011         它的十进制为:115864843

那么这里返回的就是:115864843

然后跟着方法putVal(),我们先把参数对应起来:

hash:115864843,        key:"zhang",        value:"",        onlyIfAbsent:false,        evict: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;
        if ((p = tab[i = (n - 1) & hash]) == null)
            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;
    }

刚进来,table肯定是null,则会执行这个条件

   if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;

看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;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        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;
                        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;
    }

因为第一次进,会走到条件:

            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;

相当于初始化了table,newCap是等于threshold=16,就是默认大小;

所以n=tab.length=16

然后putVal方法中第二个判断:

 if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
 }

n=16,p=null,i=0,hash=115864843即:

(p=tab[ i= (n-1) & hash])==null) 即:(null=tab[i=16-1&115864843])==null)

即:(null=tab[15&115864843]==null)

(可读性极差;这里虽然可读性差,但是减少了新建局部变量,put方面肯定高使用频率,所以就减少了多次新建局部变量,内存不会一会新建,一会儿回收,避免频繁的内存新建变量、回收变量)

计算与运算:15&115864843(与运算,2者为1,则为1)

1111&110111001111111010100001011

0000 0000 0000 0000 0000 0001 111

1101 1100 1111 1110 1010 0001 011

0000 0000 0000 0000 0000 0001 011  它的十进制为:11;

好家伙,神奇的一幕出现了,神奇在哪呢?1、一直对象的hashcode值,可以是一个非常大的数,然后跟一个threshold-1的数做异或运算,结过就是一个很小的数,这个数在threshold-1范围内,包含threshold-1本身,所以用这个算法,来计算下标值;没有用加减乘除,只用了位运算,性能是最高的;threshold是动画变化的,它的值是2的n次方,默认是16,即2的4次方2*2*2*2=16,2*2*2*2*2=16*2=32,2*2*2*2*2*2=32*2=64,

所以这里的判断为:((null=tab[11])==null),tab只是有长度,有了空间,但是里面的值还暂未添加,都是空的,所以会执行它下面的代码:

 tab[i] = newNode(hash, key, value, null);

这里就是说tab[11]=newNode(hash, key, value, null);

即:

    Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) {
        return new Node<>(hash, key, value, next);
    }

这里就是返回一个new Node<>(),就是新建了一个对象节点

    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }

看到这里,我们的else里面就不要看了,就直接到了

        else{...}
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;

这里的size++就是0+1=1,是小于默认长度16的所以不执行resize()方法;继续执行afterNodeInsertion(evict);  evict是true,上面传过来的参数;

  •         这里来总结一下:

1、在put时,hashMap会根据key的object的hashcode的值,和自身正右移16位的值做异或运算(两者相同则为0,否则为1),

2、刚进来是,table数组内无数值,为null,会初始化table值,并且大小为默认大小16,

3、在插入时,需要确定下标值,这里通过异或运算的值和threshold的值做&与运算(2者为1,则为1,否则为0),这里的下标值,一定是小于等于threshold的值,它的值是2的n次方,性能高于普通的加减乘除;这里如果table[下标值]为空,则直接新建一个节点;

4、最后,会将大小++,如果大小是小于等于threshold,则不调整大小;

分析到这里大家消化消化,消化好了,我们移步到下节,继续分析探讨:

android HashMap源码添加数据的全过程模拟(二)_简公子的博客-CSDN博客

猜你喜欢

转载自blog.csdn.net/jian11058/article/details/123047491
今日推荐