编程语言
首页 > 编程语言> > java·数据结构·hashMap

java·数据结构·hashMap

作者:互联网

特点

构造方法

相关参数

平衡与折衷

代码解析

public HashMap(int initialCapacity, float loadFactor) {
        /**初始最大容量为非负整数*/
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        /**
        * static final int MAXIMUM_CAPACITY = 1 << 30;
        * 当 initialCapacity 大于最大容量(2^30,约10.74亿)时,强制设置为容量为最大容量。
        */
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        /**
        * 加载因子为大于0的浮点数
        * public static boolean isNaN(float v) {
        *   return (v != v);
        * }
        * Float.isNaN(loadFactor):NaN(not-a-number),例如. float v = 0.0f/0.0f;
        */
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        /**赋值容量因子*/
        this.loadFactor = loadFactor;
        /**
        * 转换输入的初始最大容量为2^k,赋值给threshold作为实际最大容量
        * 这样做的意义待分析
        */
        this.threshold = tableSizeFor(initialCapacity);
    }

/**
* 获取不小于当前数的最小的2^k的值.
* 例如:31->32,65->128
*/
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;
}
public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
* 在resize()方法中设置threshold的值
* newCap = DEFAULT_INITIAL_CAPACITY;
* newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
*/
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

小结:

标签:java,hashMap,int,initialCapacity,loadFactor,threshold,数据结构,public,HashMap
来源: https://www.cnblogs.com/kunlingou/p/11067857.html