// 判断是否需要扩容 if (minCapacity - elementData.length > 0) grow(minCapacity); }
privatevoidgrow(int minCapacity){ // overflow-conscious code int oldCapacity = elementData.length; // 新数组的大小为旧数组的1.5倍 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); }
// 移除指定位置上的元素并返回其值 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; }
// 若存在对象o则移除 publicbooleanremove(Object o){ if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); returntrue; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); returntrue; } } returnfalse; }
// 清空所有对象 publicvoidclear(){ modCount++;
// clear to let GC do its work for (int i = 0; i < size; i++) elementData[i] = null;
size = 0; }
toArray方法
1 2 3 4
// 复制出一个具有原数组所有元素的新数组 public Object[] toArray() { return Arrays.copyOf(elementData, size); }
subList方法
创建出一个子List,对该List的操作将作用于到原List上
1 2 3 4 5
public List<E> subList(int fromIndex, int toIndex){ // 检查索引范围是否合法 subListRangeCheck(fromIndex, toIndex, size); returnnew SubList(this, 0, fromIndex, toIndex); }