一. HashMap类结构
二. 属性解析
1. 默认初始容量
static final int DEFAULT_INITIAL_CAPACITY =1 <<4;// aka 16
说明:默认值为16且必须为2的幂次方。
2. 最大容量
static final int MAXIMUM_CAPACITY =1 <<30;
说明:
3. 默认加载因子
static final float DEFAULT_LOAD_FACTOR =0.75f;
说明:
4. 链表转红黑树的阈值
static final int TREEIFY_THRESHOLD =8;
5. 红黑树转链表的阈值
static final int UNTREEIFY_THRESHOLD =6;
说明:
6. 链表转红黑树的最小元素个数
static final int MIN_TREEIFY_CAPACITY =64;
说明:
7. 实际加载因子
final float loadFactor;
说明:如果为指定,默认等于默认加载因子DEFAULT_LOAD_FACTOR ,即0.75.
8. 实际容量大小
int threshold;
说明:根据初始容量计算得来,初始容量向上取整为2的幂次方。如初始容量为16,则结果为16,如初始容量为14,则结算结果为16.
三. 方法解析
1. 构造函数
1)HashMap()
/*
public HashMap() {
this.loadFactor =DEFAULT_LOAD_FACTOR;// all other fields defaulted
}
*/
说明:初始化加载因子,默认为0.75.
2)HashMap(int initialCapacity)
/*
public HashMap(int initialCapacity) {
this(initialCapacity,DEFAULT_LOAD_FACTOR);
}
*/
说明:将执行的初始化容量及默认的加载因子作为参数,调用3)中的构造方法。
3)HashMap(int initialCapacity,float loadFactor)
/*
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);
}
*/
/*
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;
}
*/
说明:
如果传入的初始化容量小于0,则抛出IllegalArgumentException异常:“Illegal initial capacity”;
如果传入的初始化容量大于MAXIMUM_CAPACITY, 则将该初始化容量设置为MAXIMUM_CAPACITY;
如果加载因子小于等于0或不是浮点型的数,如0.0/0.0,则抛出IllegalArgumentException异常:“Illegal load factor”;
为实际的加载因子和实际的初始化容量赋值。
未完待续。。。