题目:RT
分析源码:ensureCapacity会保证ArrayList每次的增长不小于minCapacity,大概增长为原容量的2/3
ArrayList.add(E e)
1 public boolean add(E e) {
2 ensureCapacity(size + 1); // Increments modCount!!
3 elementData[size++] = e;
4 return true;
5 }
ArrayList.ensureCapacity(int minCapacity)
1 public void ensureCapacity(int minCapacity) {
2 modCount++;
3 int oldCapacity = elementData.length;
4 if (minCapacity > oldCapacity) {
5 Object oldData[] = elementData;
6 int newCapacity = (oldCapacity * 3)/2 + 1;
7 if (newCapacity < minCapacity)
8 newCapacity = minCapacity;
9 // minCapacity is usually close to size, so this is a win:
10 elementData = Arrays.copyOf(elementData, newCapacity);
11 }
12 }