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

来源:互联网 发布:打考勤软件 编辑:程序博客网 时间:2024/06/09 02:19

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;
0 0
原创粉丝点击