/** * Shared empty array instance used for empty instances. * 用于空实例的共享空数组实例 */ privatestaticfinal Object[] EMPTY_ELEMENTDATA = {};
/** * Shared empty array instance used for default sized empty instances. We * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when * first element is added. * 另一个共享空数组实例,用的不多,用于区别上面的EMPTY_ELEMENTDATA */ privatestaticfinal Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/** * The array buffer into which the elements of the ArrayList are stored. * The capacity of the ArrayList is the length of this array buffer. Any * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA * will be expanded to DEFAULT_CAPACITY when the first element is added. * ArrayList底层的容器 */ // Android-note: Also accessed from java.util.Collections transient Object[] elementData; // non-private to simplify nested class access
/** * The size of the ArrayList (the number of elements it contains). * 当前存放了多少个元素 并非数组大小 */ privateint size;
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) //数组之间的复制 System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work
return oldValue; }
1 2 3 4 5
publicstaticnativevoidarraycopy(Object src,//源数组 int srcPos,//源数组要复制的起始位置 Object dest,//目的数组 int destPos,//目的数组放置的起始位置 int length)//复制的长度
/** * Constructs an empty list. */ publicLinkedList(){ }
带Collection值得对象作为入参的构造函数
1 2 3 4 5 6 7 8 9 10 11 12
/** * Constructs a list containing the elements of the specified * collection, in the order they are returned by the collection's * iterator. * * @param c the collection whose elements are to be placed into this list * @throws NullPointerException if the specified collection is null */ publicLinkedList(Collection<? extends E> c){ this();//调用默认的无参构造函数 addAll(c); }
/** * 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 = new Node<>(l, e, null); //新的尾结点赋值给链表的尾结点 last = newNode; //如果之前的尾结点为空 if (l == null) first = newNode;//链表的头结点=尾结点=新结点 (相当于空链表插入第一个元素,头结点等于尾节点) else//如果不为空, l.next = newNode;//将之前的尾结点的next指针指向新的结点 //增加链表长度 size++; modCount++; }
/** * Appends the specified element to the end of this list. * * <p>This method is equivalent to {@link #add}. * * @param e the element to add */ publicvoidaddLast(E e){ linkLast(e); }
/** * Inserts the specified element at the beginning of this list. * * @param e the element to add */ publicvoidaddFirst(E e){ linkFirst(e); }
/** * Links e as first element. */ privatevoidlinkFirst(E e){ //记录头结点 final Node<E> f = first; //新建头结点 final Node<E> newNode = new Node<>(null, e, f); //新建的结点赋值给链表的头结点 first = newNode; //如果之前头结点为空 if (f == null) last = newNode;//头结点=尾结点=新建的结点 (相当于空链表插入第一个元素,头结点等于尾节点) else//如果不为空 f.prev = newNode;//之前头结点的 prev指针指向 新建的结点 //增减链表长度 size++; modCount++; }
/** * Inserts the specified element at the specified position in this list. * Shifts the element currently at that position (if any) and any * subsequent elements to the right (adds one to their indices). * * @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){ //检查是否越界 checkPositionIndex(index);
if (index == size) linkLast(element);//和 add(E e) 添加到链表末尾相同 else linkBefore(element, node(index)); } /** *检查是否越界 */ privatevoidcheckPositionIndex(int index){ if (!isPositionIndex(index)) thrownew IndexOutOfBoundsException(outOfBoundsMsg(index)); } /** * Returns the (non-null) Node at the specified element index. * 返回指定元素索引处的(非空)节点。 */ Node<E> node(int index){ // assert isElementIndex(index); //如果index在链表的前半部分,那么从first开始往后查找;否则,从last往前面查找 if (index < (size >> 1)) { //记录第一个节点 Node<E> x = first; //循环从第一个节点开始往后查,直到达到index处,返回index处元素 for (int i = 0; i < index; i++) x = x.next; return x; } else { //index在链表的后半部分,记录最后一个节点 Node<E> x = last; //循环从最后一个节点开始往前查,直到达到index处,返回index处的元素 for (int i = size - 1; i > index; i--) x = x.prev; return x; } }
/** * Inserts element e before non-null Node succ. * 在非null节点succ之前插入元素e。 */ voidlinkBefore(E e, Node<E> succ){ // assert succ != null; //记录succ的前一个结点 final Node<E> pred = succ.prev; //新建一个结点,前结点是pred ,数据是e,下一个结点是succ final Node<E> newNode = new Node<>(pred, e, succ); //将新的结点赋值给 succ的前结点 succ.prev = newNode; //如果之前的succ的前一个结点 pred 为空 if (pred == null) first = newNode;//如果为空,那么说明succ是之前的头节点.现在新节点在succ的前面,所以新节点是头节点 else pred.next = newNode;//否则,直接将succ的前一个节点pred指向新节点就可以了 //增加链表长度 size++; modCount++; }
publicbooleanaddAll(Collection<? extends E> c){ return addAll(size, c); } /** * Inserts all of the elements in the specified collection into this * list, starting at the specified position. Shifts the element * currently at that position (if any) and any subsequent elements to * the right (increases their indices). The new elements will appear * in the list in the order that they are returned by the * specified collection's iterator. * * @param index index at which to insert the first element * from the specified collection * @param c collection containing elements to be added to this list * @return {@code true} if this list changed as a result of the call * @throws IndexOutOfBoundsException {@inheritDoc} * @throws NullPointerException if the specified collection is null */ publicbooleanaddAll(int index, Collection<? extends E> c){ //1. 检查是否越界 checkPositionIndex(index); //将插入的集合转成数组 Object[] a = c.toArray(); // 记录插入元素集合的个数 int numNew = a.length; 如果个数为0,那么插入失败,不继续执行了 if (numNew == 0) returnfalse;
Node<E> pred, succ;// 目标索引的前一个结点,目标索引的结点 //判断下插入的index和链表size是否相等,相等则相当于在链表末尾插入 if (index == size) { succ = null;//index 处结点为null pred = last;// indext处前结点 为尾结点 } else {//否则,插入中间 succ = node(index);//找到index 处结点 pred = succ.prev;//记录index处前一个结点 } //循环将集合中所有元素连接到pred后面 for (Object o : a) { @SuppressWarnings("unchecked") E e = (E) o; Node<E> newNode = new Node<>(pred, e, null); //如果前一个是空,那么将新节点作为头结点 if (pred == null) first = newNode; else pred.next = newNode;//指向新节点 pred = newNode; } //判断succ是否为空,为空的话,那么集合的最后一个元素就是尾节点 if (succ == null) { last = pred; } else {//非空的话,那么将succ连接到集合的最后一个元素后面 pred.next = succ; succ.prev = pred; } //8. 链表长度+numNew size += numNew; modCount++; returntrue; }
/** * Adds the specified element as the tail (last element) of this list. * * @param e the element to add * @return {@code true} (as specified by {@link Queue#offer}) * @since 1.5 */ publicbooleanoffer(E e){ return add(e); }
1 2 3 4 5 6 7 8 9 10 11
/** * Inserts the specified element at the end of this list. * * @param e the element to insert * @return {@code true} (as specified by {@link Deque#offerLast}) * @since 1.6 */ publicbooleanofferLast(E e){ addLast(e); returntrue; }
/** * Inserts the specified element at the front of this list. * * @param e the element to insert * @return {@code true} (as specified by {@link Deque#offerFirst}) * @since 1.6 */ publicbooleanofferFirst(E e){ addFirst(e); returntrue; }
/** * Retrieves and removes the head (first element) of this list. *移除链表第一个元素 * @return the head of this list * @throws NoSuchElementException if this list is empty * @since 1.5 */ public E remove(){ return removeFirst(); } /** * Removes and returns the first element from this list. *移除和返回 链表的第一个元素 * @return the first element from this list * @throws NoSuchElementException if this list is empty */ public E removeFirst(){ final Node<E> f = first; if (f == null) thrownew NoSuchElementException(); return unlinkFirst(f); } /** * Unlinks non-null first node f. * 将第一个结点删掉 */ private E unlinkFirst(Node<E> f){ // assert f == first && f != null; //记录第一个结点的数据值 final E element = f.item; //记录下一个结点 final Node<E> next = f.next; //将第一个结点置空,帮助Gc 回收 f.item = null; f.next = null; // help GC //将之前头结点的下一个结点 赋值为头结点 first = next; //如果为空,则链表没有结点了, if (next == null) last = null; else//否则,将新节点的prev指针置为空 next.prev = null; //链表长度 -1 size--; modCount++; // 返回删除结点的数据值 return element; } /** * The number of times this list has been <i>structurally modified</i>. * Structural modifications are those that change the size of the * list, or otherwise perturb it in such a fashion that iterations in * progress may yield incorrect results. */ protectedtransientint modCount = 0;
/** * Removes the element at the specified position in this list. Shifts any * subsequent elements to the left (subtracts one from their indices). * Returns the element that was removed from the list. */ public E remove(int index){ ////检查入参是否合法/越界 checkElementIndex(index); ////node(index)找到index处的节点 return unlink(node(index));//删除index处的结点 }
/** * Removes the last occurrence of the specified element in this * list (when traversing the list from head to tail). If the list * does not contain the element, it is unchanged. * 遍历时是从尾节点开始往前查找的. */ publicbooleanremoveLastOccurrence(Object o){ if (o == null) { for (Node<E> x = last; x != null; x = x.prev) { if (x.item == null) { unlink(x); returntrue; } } } else { for (Node<E> x = last; x != null; x = x.prev) { if (o.equals(x.item)) { unlink(x); returntrue; } } } returnfalse; }
/** * Retrieves and removes the head (first element) of this list. * * @return the head of this list, or {@code null} if this list is empty * @since 1.5 */ public E poll(){ final Node<E> f = first; return (f == null) ? null : unlinkFirst(f); }
/** * Pops an element from the stack represented by this list. In other * words, removes and returns the first element of this list. * * <p>This method is equivalent to {@link #removeFirst()}. * * @return the element at the front of this list (which is the top * of the stack represented by this list) * @throws NoSuchElementException if this list is empty * @since 1.6 */ public E pop(){ return removeFirst(); }
/** * Replaces the element at the specified position in this list with the * specified element. * * @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){ //检查是否越界 checkElementIndex(index); //找到index处节点 Node<E> x = node(index); //保存该节点旧值 E oldVal = x.item; //替换为新值 x.item = element; //将旧值返回 return oldVal; }
/** * Retrieves, but does not remove, the head (first element) of this list. * * @return the head of this list * @throws NoSuchElementException if this list is empty * @since 1.5 */ public E element(){ return getFirst(); } /** * Returns the first element in this list. * * @return the first element in this list * @throws NoSuchElementException if this list is empty */ public E getFirst(){ final Node<E> f = first; if (f == null) thrownew NoSuchElementException(); return f.item; }
/** * Returns the last element in this list. * * @return the last element in this list * @throws NoSuchElementException if this list is empty */ public E getLast(){ final Node<E> l = last; if (l == null) thrownew NoSuchElementException(); return l.item; }
/** * Returns the element at the specified position in this list. * * @param index index of the element to return * @return the element at the specified position in this list * @throws IndexOutOfBoundsException {@inheritDoc} */ public E get(int index){ checkElementIndex(index); return node(index).item; }