1、 ArrayList默认的初始化因子大小是10。
/**
* Constructs an empty list with an initial capacity of ten.//一般初始化因子为10
*/
public ArrayList() {
this(10);// 调用2中的ArrayList(int initialCapacity);
}
2、用来生成一个大小为initialCapacity的ArrayList。其底层实现为一Object数组。
/**
* Constructs an empty list with the specified initial capacity.//用一个初始容量来构建一个空的list
*
* @param initialCapacity the initial capacity of the list.
* @exception IllegalArgumentException if the specified initial capacity
* is negative
*/
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = (E[])new Object[initialCapacity];
}
3、添加一个元素到列表的末尾。
/**
* Appends the specified element to the end of this list.
*
* @param o element to be appended to this list.
* @return <tt>true</tt> (as per the general contract of Collection.add).
*/
public boolean add(E o) {
ensureCapacity(size + 1); // Increments modCount!!
elementData[size++] = o;
return true;
}
4、当添加一个元素时,如果列表已满,这是就要添加列表容量。新的容量为(原容量* 3)/2 + 1。
/**
* Increases the capacity of this <tt>ArrayList</tt> instance, if
* necessary, to ensure that it can hold at least the number of elements
* specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity.
*/
public void ensureCapacity(int minCapacity) {
modCount++;
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
Object oldData[] = elementData;
int newCapacity = (oldCapacity * 3)/2 + 1;
if (newCapacity < minCapacity)
newCapacity = minCapacity;
elementData = (E[])new Object[newCapacity];
System.arraycopy(oldData, 0, elementData, 0, size);
}
}
5、删除列表中指定位置的元素,将后面的元素前移。
/**
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*
* @param index the index of the element to removed.
* @return the element that was removed from the list.
* @throws IndexOutOfBoundsException if index out of range <tt>(index
* < 0 || index >= size())</tt>.
*/
public E remove(int index) {
RangeCheck(index);
modCount++;
E oldValue = elementData[index];
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work
return oldValue;
}