# 深入理解HashMap(三): 关键源码逐行分析之构造函数

## 构造函数

HashMap 共有四个构造函数

``````public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {

// 默认初始大小 16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

// 默认负载因子 0.75
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;

transient Node<K,V>[] table;

// 没有指定时, 使用默认值
// 即默认初始大小16, 默认负载因子 0.75
public HashMap() {
}

// 指定初始大小, 但使用默认负载因子
// 注意这里其实是调用了另一个构造函数
public HashMap(int initialCapacity) {
}

// 指定初始大小和负载因子
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
throw new IllegalArgumentException("Illegal load factor: " +
this.threshold = tableSizeFor(initialCapacity);
}

// 利用已经存在的map创建HashMap
public HashMap(Map<? extends K, ? extends V> m) {
putMapEntries(m, false);
}

}
``````

``this.threshold = tableSizeFor(initialCapacity);``

`threshold` 这个值在初始化table时, 就代表了数组的初始大小, 这个我们到后面用到的时候讲.

``````/**
* 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;
}``````

tableSizeFor这个方法用于找到大于等于initialCapacity的最小的2的幂, 这个算法还是很精妙的, 这里我稍微解释一下:

``````final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
if (table == null) { // pre-size
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
threshold = tableSizeFor(t);
}
else if (s > threshold)
resize();
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
putVal(hash(key), key, value, false, evict);
}
}
}``````

`resize``putVal` 方法我们以后再细讲.

## 总结

``````HashMap()
HashMap(int initialCapacity)

(完)

##### ChiuCheng

Talk is cheap, show me the code！

1.1k 声望
575 粉丝
0 条评论