/** * 在list后面插入一个元素 * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) */ publicbooleanadd(E e){ ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; returntrue; }
/** * 指定插入位置(下标)插入元素 * * @param index index at which the specified element is to be inserted * @param element element to be inserted * @throws IndexOutOfBoundsException {@inheritDoc} */ publicvoidadd(int index, E element){ rangeCheckForAdd(index);
privatevoidgrow(int minCapacity){ // overflow-conscious code int oldCapacity = elementData.length; //新的容量 = 旧的容量加+旧的容量的一半 int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; //如果新的容量超过Integer.MAX_VALUE就会溢出,抛出异常 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); }
4 set方法
set方法用于替换指定位置的元素
java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/** * 替换指定位置的元素 * * @param index index of the element to replace * @param element element to be stored at the specified position * @return the element previously at the specified position * @throws IndexOutOfBoundsException {@inheritDoc} */ public E set(int index, E element){ // 先检查index rangeCheck(index);
E oldValue = elementData(index); elementData[index] = element; return oldValue; }
public E remove(int index){ if (index >= size) thrownew IndexOutOfBoundsException(outOfBoundsMsg(index));
modCount++; // 返回被删除的元素值 E oldValue = (E) elementData[index];
int numMoved = size - index - 1; if (numMoved > 0) // 将 index + 1 及之后的元素向前移动一位,覆盖被删除值 System.arraycopy(elementData, index+1, elementData, index, numMoved); // 将最后一个元素置空,并将 size 值减 1 elementData[--size] = null; // clear to let GC do its work
return oldValue; }
E elementData(int index){ return (E) elementData[index]; }
/删除指定元素,若元素重复,则只删除下标最小的元素 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; }
//快速删除,不做边界检查,也不返回删除的元素值 privatevoidfastRemove(int index){ modCount++; 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 }