java中的容器-hashMap
java的大部分容器都有一個(gè)須要了解的問(wèn)題,就是什么時(shí)候須要擴(kuò)張
看看hashMap的實(shí)現(xiàn) ,兩個(gè)關(guān)鍵的值
1,hashMap的默認(rèn)容量
static final int DEFAULT_INITIAL_CAPACITY = 16;
默認(rèn)的load factor
static final float DEFAULT_LOAD_FACTOR = 0.75f;
擴(kuò)張相關(guān)的函數(shù)
? 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);
?}
?結(jié)論,在建立HashMap的時(shí)候可以考慮一下是否傳入Load Factor和capacity的值來(lái)優(yōu)化性能,
?漸少擴(kuò)張次數(shù)(load factor和initial capacity), 或者漸少空間浪費(fèi)(loadFacotr)
posted on 2006-11-03 17:42 dreamstone 閱讀(456) 評(píng)論(0) 編輯 收藏 所屬分類: jdk相關(guān)