关于HashMap的默认初始大小,你知道怎么计算吗?

关于HashMap的默认初始大小:
源码:
public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

public HashMap(int initialCapacity, float loadFactor) {
    ... // 一些校验判断
    this.loadFactor = loadFactor;
    this.threshold = tableSizeFor(initialCapacity);
}

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;
}
实例:
Map map = new HashMap(5);

即输入cap为5,计算:
0000 0101	cap		5

0000 0100	n		4
0000 0010	n>>>1
0000 0110	n|n>>>1		6

0000 0001	n>>>2
0000 0111	n|n>>>2		7

0000 0000	n>>>4
0000 0111	n|n>>>4		7

...

最后得出:n=7 	return 8(7+1); 即初始大小为8

参考:mjzuo–JDK8内HashMap底层实现

你可能感兴趣的:(Java,java,hashmap初始大小)