HashMap的构造方法源码
无参构造方法
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; //将默认的负载因子0.75赋值给loadFactor,并没有创建数组
指定初始化容量的构造方法
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
指定初始化容量和负载因子的构造方法
public HashMap(int initialCapacity, float loadFactor) {
//如果容量小于0抛出异常
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
//如果容量大于最大容量那么就赋值最大容量
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
//如果加载因子小于0或者没有值就抛出异常
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
//设置负载因子
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
tableSizeFor()
/**
* Returns a power of two size for the given target capacity.
* 或运算都是0的时候为0有1的时候为1
* 假设cap传入的是10
*/
static final int tableSizeFor(int cap) {
//这里-1是为了防止出现我们传入了16 还进行了右移运算,假如我们输入成16 通过-1然后最后右移算出来是16
int n = cap - 1;
/*
00001001 9
00000100 4 9 >>> 1
--------------
00001101 13 9 |= 4
*/
n |= n >>> 1;
/*
00001101 13
00000011 3
---------------
00001111 15
*/
n |= n >>> 2;
/*
00001111 15
00000000 0
--------------
00001111 15
*/
n |= n >>> 4;
/*
00001111 15
00000000 0
--------------
00001111 15
*/
n |= n >>> 8;
/*
00001111 15
00000000 0
--------------
00001111 15
*/
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}