ArrayList、Vector、HashMap、HashTable是如何擴容

a) 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);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

b) Vector,默認初始10個大小,每次擴容是原容量的一倍,具體代碼如下:

public Vector() {
this(10);
} 
int newCapacity = (capacityIncrement > 0) ? (oldCapacity + capacityIncrement) : (oldCapacity * 2);
  • 1
  • 2
  • 3
  • 4

c) 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);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

d) HashTable默認初始11個大小,默認每次擴容的因子爲0.75

public Hashtable() {
this(11, 0.75f);
}
int newCapacity = oldCapacity * 2 + 1;
發佈了6 篇原創文章 · 獲贊 0 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章