ArrayList1.8
ArrayList是继承自List接口的动态数组,允许null元素,不允许并发。
ArrayList的构造方法有三种:
1.第一种是无初始化值,默认容量会赋值为10。
1 /** 2 * Constructs an empty list with an initial capacity of ten. 3 * 构造一个空的list,会在添加元素的时候给list的容量赋值或者扩容,(初始容量为10) 4 */ 5 public ArrayList() { 6 this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; //elementData是一个Object类型的空数组
}
添加一个元素:
1 /** 2 * Appends the specified element to the end of this list. 3 * list添加一个元素 4 * 5 * @param e element to be appended to this list 6 * @return <tt>true</tt> (as specified by {@link Collection#add}) 7 */ 8 public boolean add(E e) { 9 ensureCapacityInternal(size + 1); // Increments modCount!! 10 elementData[size++] = e; //添加元素 11 return true; 12 }
在添加元素之前,用ensureCapacityInternal(size + 1)先进行判断,如果加入该元素以后,容量大于了内部存储元素的数组的大小,就对该数组进行扩容。
扩容:
1 /** 2 * Increases the capacity to ensure that it can hold at least the 3 * number of elements specified by the minimum capacity argument. 4 * 5 * @param minCapacity the desired minimum capacity 6 */ 7 private void grow(int minCapacity) { 8 // overflow-conscious code 9 int oldCapacity = elementData.length; 10 int newCapacity = oldCapacity + (oldCapacity >> 1); 11 if (newCapacity - minCapacity < 0) 12 newCapacity = minCapacity; 13 if (newCapacity - MAX_ARRAY_SIZE > 0) 14 newCapacity = hugeCapacity(minCapacity); 15 // minCapacity is usually close to size, so this is a win: 16 elementData = Arrays.copyOf(elementData, newCapacity); 17 }
从代码中可以看出,扩容的方式是int newCapacity = oldCapacity + (oldCapacity >> 1); 也就是说扩容的大小是原来容量的一半,新的容量大小是原来的3/2。扩容好以后进行元素的搬迁。