1 在构造函数中,只是对成员变量赋值,并没有申请内存,初始化是lazy的。
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 m) { this.loadFactor = DEFAULT_LOAD_FACTOR; putMapEntries(m, false);}