1 在構造函數中,只是對成員變量賦值,並無申請內存,初始化是lazy的。java
2 若是已知須要放置不少元素,在構造時設置容量參數,避免resize,耗費性能。數組
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 默認初始數組大小是16個。 static final int MAXIMUM_CAPACITY = 1 << 30; static final float DEFAULT_LOAD_FACTOR = 0.75f; // 負載因子默認是0.75,即 16*0.75=12個元素時,發生擴容。 static final int TREEIFY_THRESHOLD = 8; // 鏈表轉換爲紅黑樹的節點閾值 static final int MIN_TREEIFY_CAPACITY = 64;
public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted } 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; this.threshold = tableSizeFor(initialCapacity); } // 支持經過已經存在的Map構造 public HashMap(Map<? extends K, ? extends V> m) { this.loadFactor = DEFAULT_LOAD_FACTOR; putMapEntries(m, false); }