java的大部分容器都有一个须要了解的问题,就是什么时候须要扩张
看看hashMap的实现 ,两个关键的值
1,hashMap的默认容量
static final int DEFAULT_INITIAL_CAPACITY = 16;
默认的load factor
static final float DEFAULT_LOAD_FACTOR = 0.75f;
扩张相关的函数
void addEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
if (size++ >= threshold)
resize(2 * table.length);
}
void resize(int newCapacity) {
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}
Entry[] newTable = new Entry[newCapacity];
transfer(newTable);
table = newTable;
threshold = (int)(newCapacity * loadFactor);
}
结论,在建立HashMap的时候可以考虑一下是否传入Load Factor和capacity的值来优化性能,
渐少扩张次数(load factor和initial capacity), 或者渐少空间浪费(loadFacotr)