Java LinkedList 详解 - TongtongLan/Java GitHub Wiki

Doubly-linked list implementation of the List and Deque interfaces. Implements all optional list operations, and permits all elements (including null).

Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index. 可以从list头部和尾部进行索引操作

Note that this implementation is not synchronized(非同步). If multiple threads access a linked list concurrently, and at least one of the threads modifies the list structurally, it must 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 Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:

List list = Collections.synchronizedList(new LinkedList(...));

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the Iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.(如果在迭代器创建后的任何时候,列表在结构上都被修改,除了通过迭代器自己的remove或add方法之外,迭代器将抛出一个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.

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 ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

  • 具备三个构造方法
  1. public LinkedList()

Constructs an empty list.

  1. public LinkedList(Collection<? extends E> c)

Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.

调用 public boolean addAll(Collection<? extends E> c) 方法将 Collection 对象转化为 LinkedList 类的 inner 类 Node 类型的对象,然后将 node 对象添加到双向链表中。

public LinkedList(Collection<? extends E> c)

public LinkedList(Collection<? extends E> c) {
    this();
    addAll(c);
}