/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
* 添加指定的元素到List的末尾
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // 扩充数组长度
elementData[size++] = e; // 最后一个赋值为e
return true;
}
那么它是如何扩充数组长度的呢?追踪代码来到**grow(int minCapacity)**方法:
/*
* 可以看到它是通过Arrays.copyOf方法将原数组拷贝到了一个数组长度为newCapacity的新数组里面
*/
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
/*
* 和add(int index, E element)类似,使用System.arraycopy进行自身拷贝,相当于将index后面的元素
* 像前移动了一位,覆盖掉需要删除的元素,将最后一个元素置位null,等待JVM自动回收
*/
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; // clear to let GC do its work
return oldValue;
}
2. remove(Object o)
/*
* 先通过for循环找到o所在的位置,再通过fastRemove(index)移除,实现方法和remove(int index)一样
*/
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
四. 查找元素
/*
* 查找元素就比较简单了,直接通过数组的下角标进行返回
*/
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
五. 修改元素
/*
* 修改元素也比较简单,直接通过数组的下角标进行赋值
*/
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}