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)