HashMap扩容

HahMap什么时候扩容呢?

(1)当map中k-v总数即下面的size大于threshold 的时候

if (++size > threshold)

            resize();

(2)

table=null或者table.length =0

threshold 是个什么?

HahMap在初始化的时候给threshold的赋值:

 this.threshold = tableSizeFor(initialCapacity);

//下面的方法用于找到>=cap的最小的2的幂

static final int tableSizeFor(int cap) {

        int n = cap - 1;

        n |= n >>> 1;

        n |= n >>> 2;

        n |= n >>> 4;

        n |= n >>> 8;

        n |= n >>> 16;

        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;

    }

使用HashMap的默认构造方法时候,当往map中put元素的时候首先会执行resize方法将threshols设置成

newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);



 

参考:

http://blog.csdn.net/fan2012huan/article/details/51097331

猜你喜欢

转载自xiaoxiaoxuanao.iteye.com/blog/2314954