目录java
/** * Doubly-linked list implementation of the {@code List} and {@code Deque} * interfaces. Implements all optional list operations, and permits all * elements (including {@code null}). * * <p>All of the operations perform as could be expected for a doubly-linked * list. Operations that index into the list will traverse the list from * the beginning or the end, whichever is closer to the specified index. 双链表实现了List和Deque的接口,实现全部可选列表操做,并容许全部操做元素(包括null) 对于双向链表,全部操做均可以预期。 索引到列表中的操做将从开头或结尾遍历列表,以较接近指定索引为准。
* * Note that this implementation is not synchronized.</strong> * If multiple threads access a linked list concurrently, and at least * one of the threads modifies the list structurally, it <i>must</i> be * synchronized externally. (A structural modification is any operation * that adds or deletes one or more elements; merely setting the value of * an element is not a structural modification.) This is typically * accomplished by synchronizing on some object that naturally * encapsulates the list. * * * If no such object exists, the list should be "wrapped" using the * {@link Collections#synchronizedList Collections.synchronizedList} * method. This is best done at creation time, to prevent accidental * unsynchronized access to the list:<pre> * List list = Collections.synchronizedList(new LinkedList(...));</pre> 请注意,此实现不一样步。 若是多个线程同时访问链表,而且至少有一个线程在结构上修改了列表,则必须在外部进行同步。 (结构修改是添加或删除一个或多个元素的任何操做;仅设置元素的值不是结构修改。)这一般经过同步天然封装列表的某个对象来完成。 若是不存在此类对象,则应使用Collections.synchronizedList}方法“包装”该列表。 这最好在建立时完成,以防止对列表的意外不一样步访问: List list = Collections.synchronizedList(new LinkedList(...))
* The iterators returned by this class's {@code iterator} and * {@code listIterator} methods are <i>fail-fast</i>: if the list is * structurally modified at any time after the iterator is created, in * any way except through the Iterator's own {@code remove} or * {@code add} methods, the iterator will throw a {@link * ConcurrentModificationException}. Thus, in the face of concurrent * modification, the iterator fails quickly and cleanly, rather than * risking arbitrary, non-deterministic behavior at an undetermined * time in the future. * 这个类的iterator和listIterator方法返回的迭代器是 fail-fast 机制:若是在建立迭代器以后的任什么时候候对列表进行告终构修改,除了经过Iterator本身的 remove或 add方法以外,迭代器将抛出 ConcurrentModificationException。 所以,在并发修改的状况下,迭代器快速而干净地失败,而不是在将来的未肯定时间冒任意,非肯定性行为的风险。
* <p>Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification. Fail-fast iterators * throw {@code ConcurrentModificationException} on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness: <i>the fail-fast behavior of iterators * should be used only to detect bugs.</i> 注意,迭代器的fail-fast行为是不能保证的.通常来讲,保证非同步的同步操做是不太可能的.在最优基础上,Fail-fast迭代器会抛出ConcurrentModificationException.所以,写一个为了自身正确性而依赖于这个异常的程序是不对的.迭代器的fail-fast行为应该只是用来检测bug而已.
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, java.io.Serializable
继承的类
AbstractSequentialList:抽象类,AbstractList的子类,以最大限度地减小“顺序访问”数据存储实现此接口所需的工做量node
实现的接口
List:很少说了
Deque:(标记接口)Deque接口就是双向队列,是Queue(队列)的一个子接口
Cloneable:(标记接口)表明 Object.clone() 方法能够合法地对该类实例进行按字段复制。(没有实现 Cloneable 接口的实例上调用 Object 的 clone 方法,则会致使抛出 CloneNotSupportedException 异常)
java.io.Serializable(标记接口)数组
protected transient int modCount = 0;
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;
内部类Node安全
private static class Node<E> { 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; } }
/** * Constructs an empty list. * * 构造一个空列表。 * */ public LinkedList() { }
/** * 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 */ public LinkedList(Collection<? extends E> c) { this(); addAll(c); }
/** * Returns the (non-null) Node at the specified element index. * * 返回指定元素索引处的(非null)节点。 * */ Node<E> node(int index) { // assert isElementIndex(index); if (index < (size >> 1)) { Node<E> x = first; for (int i = 0; i < index; i++) // 一个个赋值,目的是将第index个赋值 x = x.next; return x; } else { Node<E> x = last; for (int i = size - 1; i > index; i--) x = x.prev; return x; } }
/** * Links e as first element. * * 将e做为第一个元素 * */ private void linkFirst(E e) { final Node<E> f = first; // 新建一个元素为e的Node实例,next指针指向first final Node<E> newNode = new Node<>(null, e, f); // 将元素为e的Node实例做为first first = newNode; if (f == null) last = newNode; else f.prev = newNode; size++; modCount++; } /** * Inserts the specified element at the beginning of this list. * * 在list的开头添加指定元素,就是调用上方法 * * @param e the element to add */ public void addFirst(E e) { // 直接调用如上方法 linkFirst(e); }
/** * Links e as last element. */ private void linkLast(E e) { final Node<E> l = last; // 新建一个元素为e的Node实例,pre指针指向first final Node<E> newNode = new Node<>(l, e, null); // 将元素为e的Node实例做为last last = newNode; if (l == null) first = newNode; else l.next = newNode; 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 */ public void addLast(E e) { linkLast(e); } /** * Appends the specified element to the end of this list. * * <p>This method is equivalent to {@link #addLast}. */ public boolean add(E e) { linkLast(e); return true; }
/** * Inserts element e before non-null Node succ. * * 在非null节点succ以前插入元素e。 */ void linkBefore(E e, Node<E> succ) { // assert succ != null; final Node<E> pred = succ.prev; final Node<E> newNode = new Node<>(pred, e, succ); succ.prev = newNode; if (pred == null) first = newNode; else pred.next = newNode; size++; modCount++; } 此方法会被add(int index, E element)使用 public void add(int index, E element) { checkPositionIndex(index); if (index == size) linkLast(element); else linkBefore(element, node(index)); // 这里的node(index)就使用了一开始说的根据index返回对应的元素的方法 }
/** * Unlinks non-null first node f. * * 删除非空的第一个节点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 first = next; if (next == null) last = null; else next.prev = null; size--; modCount++; return element; }
/** * Unlinks non-null last node l. * * 删除非空的最后节点f */ private E unlinkLast(Node<E> l) { // assert l == last && l != null; final E element = l.item; final Node<E> prev = l.prev; l.item = null; l.prev = null; // help GC last = prev; if (prev == null) first = null; else prev.next = null; size--; modCount++; return element; }
/** * Unlinks non-null node x. * * 删除指定的非空的节点x */ E unlink(Node<E> x) { // assert x != null; final E element = x.item; final Node<E> next = x.next; final Node<E> prev = x.prev; if (prev == null) { first = next; } else { prev.next = next; x.prev = null; } if (next == null) { last = prev; } else { next.prev = prev; x.next = null; } x.item = null; size--; modCount++; return element; }
/** * Tells if the argument is the index of an existing element. */ private boolean isElementIndex(int index) { return index >= 0 && index < size; } /** * Tells if the argument is the index of a valid position for an * iterator or an add operation. */ private boolean isPositionIndex(int index) { return index >= 0 && index <= size; } /** * Constructs an IndexOutOfBoundsException detail message. * Of the many possible refactorings of the error handling code, * this "outlining" performs best with both server and client VMs. */ private String outOfBoundsMsg(int index) { return "Index: "+index+", Size: "+size; } private void checkElementIndex(int index) { if (!isElementIndex(index)) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private void checkPositionIndex(int index) { if (!isPositionIndex(index)) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); }
笔记:数据结构
大部分查改的方法都是内部调用的以上介绍的核心方法并发
public E getFirst() { final Node<E> f = first; if (f == null) throw new NoSuchElementException(); return f.item; } public E getLast() { final Node<E> l = last; if (l == null) throw new NoSuchElementException(); return l.item; } public E removeFirst() { final Node<E> f = first; if (f == null) throw new NoSuchElementException(); return unlinkFirst(f); } public E removeLast() { final Node<E> l = last; if (l == null) throw new NoSuchElementException(); return unlinkLast(l); } public void addFirst(E e) { linkFirst(e); } public void addLast(E e) { linkLast(e); } public E get(int index) { checkElementIndex(index); return node(index).item; } public E set(int index, E element) { checkElementIndex(index); Node<E> x = node(index); E oldVal = x.item; x.item = element; return oldVal; } public void add(int index, E element) { checkPositionIndex(index); if (index == size) linkLast(element); else linkBefore(element, node(index)); } public E remove(int index) { checkElementIndex(index); return unlink(node(index)); }
Queue operations. 如下为接口Queue的方法实现app
// 队列查询 public E peek() { final Node<E> f = first; return (f == null) ? null : f.item; } public E element() { return getFirst(); } // 出队 public E poll() { final Node<E> f = first; return (f == null) ? null : unlinkFirst(f); } public E remove() { return removeFirst(); } // 入队 public boolean offer(E e) { return add(e); }
笔记:ide
Deque operations 如下为双向队列Deque的方法实现
这里列出重要的四种6种方法:
看成双向队列时的入队(头或尾),出队(头或尾)四个方法;
看成栈使用时的入栈(push)和出栈(pop)两个方法;源码分析
public boolean offerFirst(E e) { addFirst(e); return true; } public boolean offerLast(E e) { addLast(e); return true; } public E pollFirst() { final Node<E> f = first; return (f == null) ? null : unlinkFirst(f); } public E pollLast() { final Node<E> l = last; return (l == null) ? null : unlinkLast(l); } /** * Pushes an element onto the stack represented by this list. In other * words, inserts the element at the front of this list. * * 将元素推送到此列表所表示的堆栈上。 换句话说,将元素插入此列表的前面。 * * <p>This method is equivalent to {@link #addFirst}. */ public void push(E e) { addFirst(e); } /** * 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()}. */ public E pop() { return removeFirst(); }
笔记:以上经过方法的分析能够得出 队列,双向队列,栈的区别ui
public boolean addAll(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. * * 从指定位置开始,将指定集合中的全部元素插入此列表。 * 将当前位置的元素(若是有)和任何后续元素向右移动(增长其索引)。 * 新元素将按照指定集合的迭代器返回的顺序出如今列表中。 * */ public boolean addAll(int index, Collection<? extends E> c) { checkPositionIndex(index); // 将c转化成数组 Object[] a = c.toArray(); int numNew = a.length; if (numNew == 0) return false; Node<E> pred, succ; if (index == size) { succ = null; pred = last; } else { succ = node(index); pred = succ.prev; } 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; } if (succ == null) { last = pred; } else { pred.next = succ; succ.prev = pred; } size += numNew; modCount++; return true; }
笔记:addAll方法单独列出来,是由于它是有参构造器须要调用的方法;
Iterator
/** * @since 1.6 */ public Iterator<E> descendingIterator() { return new DescendingIterator(); } /** * Adapter to provide descending iterators via ListItr.previous * * 经过ListItr.previous提供降序迭代器 */ private class DescendingIterator implements Iterator<E> { private final ListItr itr = new ListItr(size()); public boolean hasNext() { return itr.hasPrevious(); } public E next() { return itr.previous(); } public void remove() { itr.remove(); } }
ListIterator
/** * Returns a list-iterator of the elements in this list (in proper * sequence), starting at the specified position in the list. * Obeys the general contract of {@code List.listIterator(int)}.<p> * * 从列表中的指定位置开始,返回此列表中元素的列表迭代器(按正确顺序)。 * * The list-iterator is <i>fail-fast</i>: if the list is structurally * modified at any time after the Iterator is created, in any way except * through the list-iterator's own {@code remove} or {@code add} * methods, the list-iterator will throw a * {@code ConcurrentModificationException}. Thus, in the face of * concurrent modification, the iterator fails quickly and cleanly, rather * than risking arbitrary, non-deterministic behavior at an undetermined * time in the future. */ public ListIterator<E> listIterator(int index) { checkPositionIndex(index); // 校验是不是有效位置 return new ListItr(index); } private class ListItr implements ListIterator<E> { // 存储上一个返回的节点 private Node<E> lastReturned; // 存储即将返回的节点 private Node<E> next; // 存储即将返回的元素的index private int nextIndex; private int expectedModCount = modCount; ListItr(int index) { // assert isPositionIndex(index); next = (index == size) ? null : node(index); nextIndex = index; } public boolean hasNext() { return nextIndex < size; } public E next() { checkForComodification(); if (!hasNext()) throw new NoSuchElementException(); lastReturned = next; next = next.next; nextIndex++; return lastReturned.item; } public boolean hasPrevious() { return nextIndex > 0; } public E previous() { checkForComodification(); if (!hasPrevious()) throw new NoSuchElementException(); lastReturned = next = (next == null) ? last : next.prev; nextIndex--; return lastReturned.item; } public int nextIndex() { return nextIndex; } public int previousIndex() { return nextIndex - 1; } public void remove() { checkForComodification(); if (lastReturned == null) throw new IllegalStateException(); Node<E> lastNext = lastReturned.next; unlink(lastReturned); if (next == lastReturned) next = lastNext; else nextIndex--; lastReturned = null; expectedModCount++; } public void set(E e) { if (lastReturned == null) throw new IllegalStateException(); checkForComodification(); lastReturned.item = e; } public void add(E e) { checkForComodification(); lastReturned = null; if (next == null) linkLast(e); else linkBefore(e, next); nextIndex++; expectedModCount++; } public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); while (modCount == expectedModCount && nextIndex < size) { action.accept(next.item); lastReturned = next; next = next.next; nextIndex++; } checkForComodification(); } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
笔记:
源码版本为JDK1.8,只是对平常使用的基本操做的源码进行了分析,对于1.8的新特性并无涉及,等将主要集合类源码分析完后,之后会专门出一篇分析一下1.8中集合的新特性; 有建议或着问题的,请在文末留言,本人水平有限,有错误或理解误差,还请各位多多指导和见谅,如若转载,请代表出处;