JAVA中StringBuffer,HashMap等常見類擴容機制
阿新 • • 發佈:2019-01-03
結論:
類名 | 增長速率 | 初始值 |
---|---|---|
ArrayList | 1.5x+1 | 預設10 |
Vector | 2x | 預設10 |
HashTable | 2x+1 | 預設11 |
HashMap | 2x | 預設16 |
StringBuffer | 2x+2 | 預設16 |
StringBuilder | 2x+2 | 預設16 |
`StringBuffer、StringBuilder預設初始化是16個字元,預設增容為(原長度+1)*2,程式碼如下: //預設初始化大小 public StringBuilder() { super(16); } // 預設擴容 int newCapacity = (value.length + 1) * 2; ArrayList、Vector、HashMap、HashTable是如何擴容的 1. ArrayList,預設初始10個大小,每次擴容是原容量的一半,具體程式碼如下: public ArrayList() { this(10); } int newCapacity = (oldCapacity * 3)/2 + 1; public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length); 2. Vector,預設初始10個大小,每次擴容是原容量的兩倍,具體程式碼如下: public Vector() { this(10); } int newCapacity = (capacityIncrement > 0) ? (oldCapacity + capacityIncrement) : (oldCapacity * 2); 3. HashMap預設初始16個大小(必須是2的次方),預設每次擴容的因子為0.75,具體程式碼如下: static final int DEFAULT_INITIAL_CAPACITY = 16; static final float DEFAULT_LOAD_FACTOR = 0.75f; public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR); table = new Entry[DEFAULT_INITIAL_CAPACITY]; init(); } resize(2 * table.length); 4. HashTable預設初始11個大小,預設每次擴容的因子為0.75,具體程式碼如下: public Hashtable() { this(11, 0.75f); } int newCapacity = oldCapacity * 2 + 1;`