HashMap中重要变量:
/**
* The default initial capacity - MUST be a power of two.
*/
//初始容量,必须为 2的倍数,这里使用移位运算符<<提升效率
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* 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的31次方,并且不再进行扩容
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* The load factor used when none specified in constructor.
*/
//加载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
HashMap构造方法 (暂时不看public HashMap(Map<? extends K, ? extends V> m){...} 该方法)
public HashMap() {
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
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;
threshold = initialCapacity;
init();
}
void init() {
}
构造方法中仅仅是对初始化的参数进行了校验和赋值,并未创建数组或链表。数组是在向hashmap中放数据的时候创建的,接下来我们来看put方法:
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
//如果数组为空,那么扩充数组
inflateTable(threshold);
}
if (key == null)
return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
private void inflateTable(int toSize) {
// Find a power of 2 >= toSize 计算出 大于或等于 toSize的2的倍数的数
int capacity = roundUpToPowerOf2(toSize);
threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
table = new Entry[capacity];
initHashSeedAsNeeded(capacity);
}
粗略来看,首先是对数组table进行判空, 如果为空就扩充数组(初始table为空数组),也可理解为初始化table数组。其中threshold为阈值,用于判断是否需要调整HashMap中table的容量。threshold=容量 * 加载因子,当HashMap中存储数据的数量达到threshold时,就需要将HashMap的容量翻倍。
然后使用hash()方法获取key的hash值,并计算出key在table中的下标位置,如果该位置已经存在数据并且key相等(equals()方法返回true),则将其覆盖,否则调用addEntry()方法将其放在table中。