今日主题是源码分析之HashMap指定初始容量的构造函数(以下都是基于jdk1.8)。
HashMap可以指定初始容量大小的构造函数有两个:
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* The next size value at which to resize (capacity * load factor).
*
* @serial
*/
// (The javadoc description is true upon serialization.
// Additionally, if the table array has not been allocated, this
// field holds the initial array capacity, or zero signifying
// DEFAULT_INITIAL_CAPACITY.)
int threshold;
/**
* The load factor for the hash table.
*
* @serial
*/
final float loadFactor;
/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and load factor.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and the default load factor (0.75).
*
* @param initialCapacity the initial capacity.
* @throws IllegalArgumentException if the initial capacity is negative.
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
看第一个构造函数即可,因为第二个也是通过第一个来实现的,只是加载因子是默认值0.75 。
接下来看tableSizeFor方法:
/**
* Returns a power of two size for the given target capacity.
*/
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;
}
通过注释可以看到,我们传进来的初始容量值,经过一系列的无符号右移运算和位的或运算,最终给我们返回最接近我们指定的初始容量值的2的幂次方。
这里不需要考虑指定初始容量值为负数的情况,因为在构造函数中已经进行了判断。如果为负数,则程序将抛出异常。
为什么要先进行一步减1的操作呢?这是因为当我们指定初始容量正好是2的幂次方时,比如8,经过上述一系列的运算,最终会返回16,然而最接近于指定值的2的幂次方就是它本身。为了解决这一问题,程序首先执行了减1操作。
tableSizeFor方法的返回值赋值给了变量threshold,如果现在你还看不出来这个变量的作用也没关系,在接下来的博客中你将继续看到它的身影~