List存儲一個有序元素合集java
List接口的實現類有: ArrayList,LinkedList,Vector,Stack數組
ArrayList一個數組型的Listthis
默認容量爲10code
private static final int DEFAULT_CAPACITY = 10;
擴容對象
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方法繼承
public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; }
remove方法索引
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; }
subList內部類接口
生成subList對象ci
public List<E> subList(int fromIndex, int toIndex) { //檢查邊界 subListRangeCheck(fromIndex, toIndex, size); //生成的時SubList對象,注意this return new SubList(this, 0, fromIndex, toIndex); }
subList繼承自AbstractListelement
private final AbstractList<E> parent; private final int parentOffset; private final int offset; int size; SubList(AbstractList<E> parent, int offset, int fromIndex, int toIndex) { this.parent = parent; this.parentOffset = fromIndex; this.offset = offset + fromIndex; this.size = toIndex - fromIndex; this.modCount = ArrayList.this.modCount; }
public void add(int index, E e) { rangeCheckForAdd(index); checkForComodification(); parent.add(parentOffset + index, e); this.modCount = parent.modCount; this.size++; }
結論: