HashMap源码

HashMap源码

初始化

HashMap()

/**
 * The load factor for the hash table.
 *
 * @serial
 */
// 为hashtable设置一个负载因子
final float loadFactor;

/**
 * The load factor used when none specified in constructor.
 */
// 如果没有指定,则使用默认的负载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;

public HashMap() {
    // 使用默认的负载因子
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

HashMap(int initialCapacity)

HashMap(int initialCapacity, float loadFactor)

/**
 * 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.
 */
// 使用移位运算来计算,保证是2的幂次方,同时效率更高。容量最大为2^30
static final int MAXIMUM_CAPACITY = 1 << 30;

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

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

/**
 * 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);
    // 如果超过最大值则设置为最大值2^30
    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);
}

/**
 * Returns a power of two size for the given target capacity.
 */
// 返回的是给定容量的最接近的2的幂次方
// 假设给定cap=10,其二进制为1010
static final int tableSizeFor(int cap) {
    // n = 9 二进制=1001
    int n = cap - 1;
    // n = n | (n >>> 1)
    // n >>> 1 = 0100
    // n = (n | 0100) = 1101
    n |= n >>> 1;
    // n = n | (n >>> 2)
    // n >>> 2 = 0011
    // n =(n | 0011) = (1101 | 0011) = 1111
    n |= n >>> 2;
    // 运算结果同上
    n |= n >>> 4;
    n |= n >>> 8;
    n |= n >>> 16;
    // 此时,n= 1111 = 15
    return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; // return 16
}

类似文章