/** * Appends the specified element to the end of this list. * * <p>This method is equivalent to {@link #addLast}. * * @param e element to be appended to this list * @return {@code true} (as specified by {@link Collection#add}) */ publicbooleanadd(E e) { linkLast(e); returntrue; } /** * Links e as last element. */ 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++; } // 等等
还有一个 add(int index, E element) 在指定位置插入
先判断下标有没有越界:checkPositionIndex(index),越界就抛异常了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
publicvoidadd(int index, E element) { checkPositionIndex(index);
if (index == size) linkLast(element); else linkBefore(element, node(index)); }
privatevoidcheckPositionIndex(int index) { // 不合法 if (!isPositionIndex(index)) thrownewIndexOutOfBoundsException(outOfBoundsMsg(index)); }
// Tells if the argument is the index of a valid position for an iterator or an add operation. privatebooleanisPositionIndex(int index) { return index >= 0 && index <= size; }
会判断是不是插入末尾,要是插中间就会调 void linkBefore(E e, Node<E> succ),而这个 Node<E> node(int index) 方法就是返回了这个下标处本来的节点
/** * Removes all of the elements from this list. * The list will be empty after this call returns. */ publicvoidclear() { // Clearing all of the links between nodes is "unnecessary", but: // - helps a generational GC if the discarded nodes inhabit // more than one generation // - is sure to free memory even if there is a reachable Iterator for (Node<E> x = first; x != null; ) { Node<E> next = x.next; x.item = null; x.next = null; x.prev = null; x = next; } first = last = null; size = 0; modCount++; }
找
int indexOf(Object o) 返回此列表中指定元素首次出现的索引
会分成是不是 null 两种情况
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
publicintindexOf(Object o) { intindex=0; if (o == null) { // 是 null for (Node<E> x = first; x != null; x = x.next) { if (x.item == null) return index; index++; } } else { // 不是 null for (Node<E> x = first; x != null; x = x.next) { if (o.equals(x.item)) return index; index++; } } return -1; }
删
最基本的方法就是 E unlinkFirst(Node<E> f) 和 E unlinkLast(Node<E> l)