privatevoidgrow(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); }
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; }
privatevoidrangeCheck(int index){ if (index >= size) thrownew IndexOutOfBoundsException(outOfBoundsMsg(index)); }
在删除操作中,首先检查要删除位置的范围,不在数组长度内,抛出数组越界异常;
计算出从要删除的位置开始,到数组最后一位的元素个数,即要像前移动一位的元素个数;
从 index + 1 开始,以及往后的元素,向前移动一位,并将数组的最后一位元素置为空,size 减少一个,将删除的值返回。
可见,顺序存储的指定位置的增删需要移动多个元素,效率不高。
修改和查询
1 2 3 4 5 6 7 8 9 10 11 12 13 14
public E set(int index, E element){ rangeCheck(index);
E oldValue = elementData(index); elementData[index] = element; return oldValue; }
public E next(){ checkForComodification(); int i = cursor; if (i >= size) thrownew NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) thrownew ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; }
publicvoidremove(){ if (lastRet < 0) thrownew IllegalStateException(); checkForComodification();
Copyright Declaration: This station is mainly used to sort out incomprehensible knowledge. I have not fully mastered most of the content. Please refer carefully.