transient int size = 0;//元素个数 /** * Pointer to first node. * Invariant: (first == null && last == null) || * (first.prev == null && first.item != null) */ transient Node<E> first;//头节点 /** * Pointer to last node. * Invariant: (first == null && last == null) || * (last.next == null && last.item != null) */ transient Node<E> last;//尾节点 /** * Constructs an empty list. */ public LinkedList() {//构造一个空的list }
private static class Node<E> {//Node是一个双向链表 E item; Node<E> next; Node<E> prev; Node(Node<E> prev, E element, Node<E> next) { this.item = element; this.next = next; this.prev = prev; } }
/** * 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}) */ public boolean add(E e) {//添加元素到尾节点 linkLast(e); return true; }
/** * Links e as last element. */ void linkLast(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; size++; modCount++; }
/** * 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;头节点的下一个节点 f.item = null;//清空元素 f.next = null; // help GC//指控元素指向,让gc回收对象 first = next; if (next == null) last = null; else next.prev = null; size--; modCount++; return element; }