public E remove(int index) { rangeCheck(index); modCount++; EoldValue= elementData(index); intnumMoved= 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; }
publicbooleanremove(Object o) { if (o == null) { for (intindex=0; index < size; index++) if (elementData[index] == null) { fastRemove(index); returntrue; } } else { // 遍历数组 for (intindex=0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); returntrue; } } returnfalse; }
privatevoidfastRemove(int index) { modCount++; intnumMoved= size - index - 1; if (numMoved > 0) // 同样也要数组重组 System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work }
获取元素
1 2 3 4 5 6 7 8 9
// ArrayList是基于数组实现的,所以在获取元素的时候非常快 public E get(int index) { rangeCheck(index); return elementData(index); }
E elementData(int index) { return (E) elementData[index]; }
voidlinkLast(E e) { final Node<E> l = last; final Node<E> newNode = newNode<>(l, e, null); last = newNode; if (l == null) first = newNode; else l.next = newNode; size++; modCount++; }
// 从链头或者链尾查找元素 publicbooleanremove(Object o) { if (o == null) { for (Node<E> x = first; x != null; x = x.next) { if (x.item == null) { unlink(x); returntrue; } } } else { for (Node<E> x = first; x != null; x = x.next) { if (o.equals(x.item)) { unlink(x); returntrue; } } } returnfalse; }
public E remove(int index) { checkElementIndex(index); return unlink(node(index)); }
获取元素
1 2 3 4
public E get(int index) { checkElementIndex(index); return node(index).item; }