package java.util;
import java.util.function.Consumer;
/**
* List和Deque接口的雙向鏈表實現,實現了所有可選接口,允許空值null
* 支持所有雙向鏈表應該支持的操作,深入鏈表的操作都是從鏈表頭遍歷到鏈表尾
* 該實現不支持併發。多線程訪問,至少一個線程修改列表結構時,需要外部同步,如:
* List list = Collections.synchronizedList(new LinkedList(...));
* iterator和listIterator返回的迭代器都是快速失敗(fail-fast)的,併發情況下修改後果未定義
* 此功能(fail-fast)只用於調試bug
*/
/**
* LinkedList和ArrayList一樣都實現了List的接口,但是它執行插入和刪除操作時比ArrayList更加高效,因爲它是基於鏈表的。
* 基於鏈表也決定了它在隨機訪問方面要比ArrayList遜色一點
* LinkedList還提供了一些可以使其作爲棧、隊列、雙端隊列的方法。
* 這些方法中有些彼此之間只是名稱的區別,以使得這些名字在特定的上下文中顯得更加的合適
* LinkedList繼承自AbstractSequenceList、實現了List及Deque接口。
* 其實,AbstractSequenceList已經實現了List接口,這裏標註出List只是更加清晰而已。
* AbstractSequenceList提供了List接口骨幹性的實現以減少實現List接口的複雜度。
* Deque接口定義了雙端隊列的操作
*/
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
//LinkedList對象裏存儲的元素個數
transient int size = 0;
/**
* 指向第一個結點的指針
* Invariant: (first == null && last == null) ||
* (first.prev == null && first.item != null)
*/
transient Node<E> first;
/**
* 指向最後一個結點的指針
* Invariant: (first == null && last == null) ||
* (last.next == null && last.item != null)
*/
transient Node<E> last;
/**
* 構造函數1:構造一個空鏈表
* first=null,last=null,即代表列表爲空
*/
public LinkedList() {
}
/**
* 構造函數2:構造一個列表,包含指定集合中的元素,順序按照集合的迭代器返回的順序
* @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);
}
/**
* 從頭部插入元素e,結點e成爲新的頭結點
*/
private void linkFirst(E e) {
final Node<E> f = first;
//newNode前驅結點爲null,後繼結點爲f=first,結點值爲e
final Node<E> newNode = new Node<>(null, e, f);
first = newNode;
//newNode爲第一個結點
if (f == null)
last = newNode;
//建立原頭結點與新頭結點的鏈接
else
f.prev = newNode;
size++;
modCount++;
}
/**
* 從尾部插入元素e,結點e成爲新的尾結點
*/
void linkLast(E e) {
final Node<E> l = last;
//新建一個前驅爲l=last,後繼結點爲null,結點值爲e的newNode
final Node<E> newNode = new Node<>(l, e, null);
//新的尾結點
last = newNode;
//如果newNode是唯一的一個結點
if (l == null)
first = newNode;
//建立原尾結點與新尾結點的鏈接
else
l.next = newNode;
size++;
modCount++;
}
/**
* 在一個非空後繼結點succ前插入元素e
*/
void linkBefore(E e, Node<E> succ) {
// 假設succ!=null
final Node<E> pred = succ.prev;
//新建一個前驅爲pred,後繼爲succ,結點值爲e
final Node<E> newNode = new Node<>(pred, e, succ);
succ.prev = newNode;
//前驅爲空
if (pred == null)
first = newNode;
//前驅非空
else
pred.next = newNode;
size++;
modCount++;
}
/**
* 刪除非空首結點
*/
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自減
size--;
//修改modCount
modCount++;
return element;
}
/**
* 刪除非空尾結點
*/
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;
}
/**
* 刪除非空結點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;
//前驅爲空,x是首節點
if (prev == null) {
first = next;
} else {
prev.next = next;
x.prev = null;
}
//後繼爲空,x是尾結點
if (next == null) {
last = prev;
} else {
next.prev = prev;
x.next = null;
}
//解除x的引用
x.item = null;
size--;
//修改modCount
modCount++;
return element;
}
/**
* 返回列表中的第一個元素
* @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)
throw new NoSuchElementException();
return f.item;
}
/**
* 返回列表中最後一個元素
* @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)
throw new NoSuchElementException();
return l.item;
}
/**
* 刪除並返回列表的第一個元素,使用unlinkFirst(f)
* @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)
throw new NoSuchElementException();
return unlinkFirst(f);
}
/**
* 刪除並返回列表的最後一個元素,使用unlinkLast(l)
* @return the last element from this list
* @throws NoSuchElementException if this list is empty
*/
public E removeLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
}
/**
* 在列表開頭處插入指定元素,使用linkFirst
* @param e the element to add
*/
public void addFirst(E e) {
linkFirst(e);
}
/**
* 在列表結尾插入指定元素,使用linkLast,與add等效
* @param e the element to add
*/
public void addLast(E e) {
linkLast(e);
}
/**
* Returns {@code true} if this list contains the specified element.
* More formally, returns {@code true} if and only if this list contains
* at least one element {@code e} such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.
*
* @param o element whose presence in this list is to be tested
* @return {@code true} if this list contains the specified element
*/
public boolean contains(Object o) {
return indexOf(o) != -1;
}
/**
* 返回列表中元素數目
* @return the number of elements in this list
*/
public int size() {
return size;
}
/**
* 在列表尾結點後添加元素,使用linklast
* <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;
}
/**
* 刪除首個與指定對象相等的元素,使用unlink刪除
* @param o element to be removed from this list, if present
* @return {@code true} if this list contained the specified element
*/
public boolean remove(Object o) {
if (o == null) {
//順序遍歷,找到指定元素
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
//順序遍歷
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
/**
* 將指定集合中所有元素添加到列表中,併發修改未定義
* @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 NullPointerException if the specified collection is null
*/
public boolean addAll(Collection<? extends E> c) {
//調用addAll(index, c)
return addAll(size, c);
}
/**
* 在指定index之後插入集合c中的所有元素,當前位置及其所有後繼元素向後移動
* @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
*/
public boolean addAll(int index, Collection<? extends E> c) {
//範圍檢查
checkPositionIndex(index);
Object[] a = c.toArray();
int numNew = a.length;
//若需要插入的結點個數爲0則返回false,表示沒有插入元素
if (numNew == 0)
return false;
//succ保存index處的結點,插入位置如果是size,則在尾結點後面插入,否則獲取index處的結點
//pred保存index處的前驅結點,插入時需要修改這個結點的next引用
Node<E> pred, succ;
if (index == size) {
succ = null;
pred = last;
} else {
succ = node(index);
pred = succ.prev;
}
//按順序將a數組中的第一個元素插入到index處,將之後的元素插在這個元素後面
for (Object o : a) {
@SuppressWarnings("unchecked") E e = (E) o;
//新建一個前驅爲pred,後繼爲null,結點值爲e的結點newNode
Node<E> newNode = new Node<>(pred, e, null);
//考慮首節點
if (pred == null)
first = newNode;
else
pred.next = newNode;
pred = newNode;
}
//succ爲null,則當前pred爲最後一個元素
if (succ == null) {
last = pred;
} else {
//將succ及其之後的所有元素鏈到pred上
pred.next = succ;
succ.prev = pred;
}
//修改size,modCount
size += numNew;
modCount++;
return true;
}
/**
* 移除列表中所有元素
*/
public void clear() {
// 清除所有節點之間的鏈接可能沒什麼必要,但是:
// -如果丟棄的結點處於初代以上且沒有可達迭代器,
// -這就幫助分代GC回收自由空間
for (Node<E> x = first; x != null; ) {
Node<E> next = x.next;
//解除兩兩結點之間引用關係
x.item = null;
x.next = null;
x.prev = null;
x = next;
}
//first=null和last=null表示列表爲空
first = last = null;
size = 0;
modCount++;
}
// 位置訪問操作Positional Access Operations
/**
* 返回列表中指定位置的元素
* @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);
//返回index下標處的元素
return node(index).item;
}
/**
* 替換指定下標的元素爲指定元素
* @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);
//獲取元素結點
Node<E> x = node(index);
E oldVal = x.item;
x.item = element;
return oldVal;
}
/**
* 在指定下標index處插入元素element,當前節點及其後繼向後移動
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) {
//範圍檢查
checkPositionIndex(index);
//在鏈表末尾處添加
if (index == size)
linkLast(element);
//在鏈表中添加
else
linkBefore(element, node(index));
}
/**
* 刪除指定下標處的元素,其後繼結點向前移動一位,返回刪除的元素
* @param index the index of the element to be removed
* @return the element previously at the specified position
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E remove(int index) {
//範圍檢查
checkElementIndex(index);
//刪除結點
return unlink(node(index));
}
/**
* 檢查下標index是否當前存在的元素
*/
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}
/**
* 爲迭代器iterator或添加操作add驗證index參數是否合法
*/
private boolean isPositionIndex(int index) {
//判斷index是否超過了鏈表長度或小於0
return index >= 0 && index <= size;
}
/**
* 構造一個異常IndexOutOfBoundsException的詳細信息對象
*/
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
//對index範圍檢查
private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* 返回指定下標index處的非空結點
*/
Node<E> node(int index) {
// 假設 isElementIndex(index)返回true;
//沒超過一半,從first結點開始向後遍歷尋找結點
if (index < (size >> 1)) {
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
//超過一半,從last結點開始向前遍歷尋找結點
Node<E> x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
// 搜索操作
/**
* 返回列表中指定對象首次出現的下標,不存在則返回-1
* @param o element to search for
* @return the index of the first occurrence of the specified element in
* this list, or -1 if this list does not contain the element
*/
public int indexOf(Object o) {
int index = 0;
//查詢對象爲空
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null)
return index;
index++;
}
} else {
//集合中不支持基本類型,都是類類型,所以都用equals比較
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item))
return index;
index++;
}
}
return -1;
}
/**
* 返回列表中指定對象最後一次出現的下標,不存在則返回-1
* @param o element to search for
* @return the index of the last occurrence of the specified element in
* this list, or -1 if this list does not contain the element
*/
public int lastIndexOf(Object o) {
//從後向前遍歷,找到的第一個元素即爲所求
int index = size;
if (o == null) {
//搜索對象爲空null
for (Node<E> x = last; x != null; x = x.prev) {
index--;
if (x.item == null)
return index;
}
} else {
//搜索對象非空
for (Node<E> x = last; x != null; x = x.prev) {
index--;
if (o.equals(x.item))
return index;
}
}
return -1;
}
// 隊列操作
/**
* 取但不移除列表頭結點
* @return the head of this list, or {@code null} if this list is empty
*/
public E peek() {
//返回頭結點
final Node<E> f = first;
return (f == null) ? null : f.item;
}
/**
* 取但不移除列表頭結點
* @return the head of this list
* @throws NoSuchElementException if this list is empty
*/
public E element() {
//返回頭結點
return getFirst();
}
/**
* 取並移除列表頭結點
* @return the head of this list, or {@code null} if this list is empty
*/
public E poll() {
final Node<E> f = first;
//返回並移除頭結點
return (f == null) ? null : unlinkFirst(f);
}
/**
* 返回並移除頭結點
* @return the head of this list
* @throws NoSuchElementException if this list is empty
*/
public E remove() {
//返回並移除頭結點
return removeFirst();
}
/**
* 添加指定元素作爲列表尾結點
* @param e the element to add
* @return {@code true} (as specified by {@link Queue#offer})
*/
public boolean offer(E e) {
return add(e);
}
// 雙端隊列操作(棧操作)
/**
* 插入指定元素到首節點之前
* @param e the element to insert
* @return {@code true} (as specified by {@link Deque#offerFirst})
*/
public boolean offerFirst(E e) {
//首節點之前插入元素
addFirst(e);
return true;
}
/**
* 在列表尾結點插入指定元素
* @param e the element to insert
* @return {@code true} (as specified by {@link Deque#offerLast})
*/
public boolean offerLast(E e) {
//在尾結點之後插入元素
addLast(e);
return true;
}
/**
* 取但不移除首節點,如果列表爲空,返回null
* @return the first element of this list, or {@code null}
* if this list is empty
*/
public E peekFirst() {
final Node<E> f = first;
//返回首節點
return (f == null) ? null : f.item;
}
/**
* 取但不刪除列表尾結點,列表爲空返回null
* @return the last element of this list, or {@code null}
* if this list is empty
*/
public E peekLast() {
final Node<E> l = last;
//返回尾結點
return (l == null) ? null : l.item;
}
/**
* 返回並移除列表首節點,列表爲空返回null
* @return the first element of this list, or {@code null} if
* this list is empty
*/
public E pollFirst() {
final Node<E> f = first;
//返回並刪除首結點
return (f == null) ? null : unlinkFirst(f);
}
/**
* 返回並刪除列表尾結點,列表爲空返回null
* @return the last element of this list, or {@code null} if
* this list is empty
*/
public E pollLast() {
final Node<E> l = last;
//返回並移除尾結點
return (l == null) ? null : unlinkLast(l);
}
/**
* 向列表表示的棧中壓入元素,等價於addFirst
* @param e the element to push
*/
public void push(E e) {
addFirst(e);
}
/**
* 從棧中移除並返回一個元素,即刪除並返回列表首元素,等價於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
*/
public E pop() {
return removeFirst();
}
/**
* 刪除第一次出現的指定元素,如果不包含該元素,沒有變化
* @param o element to be removed from this list, if present
* @return {@code true} if the list contained the specified element
*/
public boolean removeFirstOccurrence(Object o) {
//刪除指定元素
return remove(o);
}
/**
* 刪除最後一次出現的指定元素,若沒有,不做改變
* @param o element to be removed from this list, if present
* @return {@code true} if the list contained the specified element
*/
public boolean removeLastOccurrence(Object o) {
//搜索空對象
if (o == null) {
for (Node<E> x = last; x != null; x = x.prev) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
//搜索非空對象
for (Node<E> x = last; x != null; x = x.prev) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
//沒有則返回false
return false;
}
/**
* 返回列表的一個從指定位置開始的list迭代器,遵循listIterator(int)的通用規範
* 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.
*
* @param index index of the first element to be returned from the
* list-iterator (by a call to {@code next})
* @return a ListIterator of the elements in this list (in proper
* sequence), starting at the specified position in the list
* @throws IndexOutOfBoundsException {@inheritDoc}
* @see List#listIterator(int)
*/
public ListIterator<E> listIterator(int index) {
//範圍檢查
checkPositionIndex(index);
return new ListItr(index);
}
private class ListItr implements ListIterator<E> {
private Node<E> lastReturned = null;
private Node<E> next;
private int nextIndex;
private int expectedModCount = modCount;
ListItr(int index) {
// 假設isPositionIndex(index)返回true;
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();
}
}
//鏈表內部結點Node<E>
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;
}
}
public Iterator<E> descendingIterator() {
return new DescendingIterator();
}
/**
* Adapter to provide descending iterators via 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();
}
}
@SuppressWarnings("unchecked")
private LinkedList<E> superClone() {
try {
return (LinkedList<E>) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
/**
* Returns a shallow copy of this {@code LinkedList}. (The elements
* themselves are not cloned.)
*
* @return a shallow copy of this {@code LinkedList} instance
*/
public Object clone() {
LinkedList<E> clone = superClone();
// Put clone into "virgin" state
clone.first = clone.last = null;
clone.size = 0;
clone.modCount = 0;
// Initialize clone with our elements
for (Node<E> x = first; x != null; x = x.next)
clone.add(x.item);
return clone;
}
/**
* 返回一個包含列表所有元素的數組(按照從頭到尾的順序),返回的數組是安全的,因爲鏈表內部不存在對它的引用
* 它是分配了一個新數組,所以調用者可以任意修改返回的數組,不會對鏈表造成影響
* @return an array containing all of the elements in this list
* in proper sequence
*/
public Object[] toArray() {
Object[] result = new Object[size];
int i = 0;
//從頭到尾遍歷鏈表
for (Node<E> x = first; x != null; x = x.next)
result[i++] = x.item;
return result;
}
/**
* Returns an array containing all of the elements in this list in
* proper sequence (from first to last element); the runtime type of
* the returned array is that of the specified array. If the list fits
* in the specified array, it is returned therein. Otherwise, a new
* array is allocated with the runtime type of the specified array and
* the size of this list.
*
* <p>If the list fits in the specified array with room to spare (i.e.,
* the array has more elements than the list), the element in the array
* immediately following the end of the list is set to {@code null}.
* (This is useful in determining the length of the list <i>only</i> if
* the caller knows that the list does not contain any null elements.)
*
* <p>Like the {@link #toArray()} method, this method acts as bridge between
* array-based and collection-based APIs. Further, this method allows
* precise control over the runtime type of the output array, and may,
* under certain circumstances, be used to save allocation costs.
*
* <p>Suppose {@code x} is a list known to contain only strings.
* The following code can be used to dump the list into a newly
* allocated array of {@code String}:
*
* <pre>
* String[] y = x.toArray(new String[0]);</pre>
*
* Note that {@code toArray(new Object[0])} is identical in function to
* {@code toArray()}.
*
* @param a the array into which the elements of the list are to
* be stored, if it is big enough; otherwise, a new array of the
* same runtime type is allocated for this purpose.
* @return an array containing the elements of the list
* @throws ArrayStoreException if the runtime type of the specified array
* is not a supertype of the runtime type of every element in
* this list
* @throws NullPointerException if the specified array is null
*/
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
//如果a數組的長度不夠,重新申請足夠的數組,使用Java反射
if (a.length < size)
a = (T[])java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size);
int i = 0;
Object[] result = a;
//從頭到尾遍歷鏈表
for (Node<E> x = first; x != null; x = x.next)
result[i++] = x.item;
if (a.length > size)
a[size] = null;
return a;
}
private static final long serialVersionUID = 876323262645176354L;
/**
* Saves the state of this {@code LinkedList} instance to a stream
* (that is, serializes it).
*
* @serialData The size of the list (the number of elements it
* contains) is emitted (int), followed by all of its
* elements (each an Object) in the proper order.
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
// Write out any hidden serialization magic
s.defaultWriteObject();
// Write out size
s.writeInt(size);
// Write out all elements in the proper order.
for (Node<E> x = first; x != null; x = x.next)
s.writeObject(x.item);
}
/**
* Reconstitutes this {@code LinkedList} instance from a stream
* (that is, deserializes it).
*/
@SuppressWarnings("unchecked")
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in any hidden serialization magic
s.defaultReadObject();
// Read in size
int size = s.readInt();
// Read in all elements in the proper order.
for (int i = 0; i < size; i++)
linkLast((E)s.readObject());
}
/**
* Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
* and <em>fail-fast</em> {@link Spliterator} over the elements in this
* list.
*
* <p>The {@code Spliterator} reports {@link Spliterator#SIZED} and
* {@link Spliterator#ORDERED}. Overriding implementations should document
* the reporting of additional characteristic values.
*
* @implNote
* The {@code Spliterator} additionally reports {@link Spliterator#SUBSIZED}
* and implements {@code trySplit} to permit limited parallelism..
*
* @return a {@code Spliterator} over the elements in this list
* @since 1.8
*/
@Override
public Spliterator<E> spliterator() {
return new LLSpliterator<E>(this, -1, 0);
}
/** A customized variant of Spliterators.IteratorSpliterator */
static final class LLSpliterator<E> implements Spliterator<E> {
static final int BATCH_UNIT = 1 << 10; // batch array size increment
static final int MAX_BATCH = 1 << 25; // max batch array size;
final LinkedList<E> list; // null OK unless traversed
Node<E> current; // current node; null until initialized
int est; // size estimate; -1 until first needed
int expectedModCount; // initialized when est set
int batch; // batch size for splits
LLSpliterator(LinkedList<E> list, int est, int expectedModCount) {
this.list = list;
this.est = est;
this.expectedModCount = expectedModCount;
}
final int getEst() {
int s; // force initialization
final LinkedList<E> lst;
if ((s = est) < 0) {
if ((lst = list) == null)
s = est = 0;
else {
expectedModCount = lst.modCount;
current = lst.first;
s = est = lst.size;
}
}
return s;
}
public long estimateSize() { return (long) getEst(); }
public Spliterator<E> trySplit() {
Node<E> p;
int s = getEst();
if (s > 1 && (p = current) != null) {
int n = batch + BATCH_UNIT;
if (n > s)
n = s;
if (n > MAX_BATCH)
n = MAX_BATCH;
Object[] a = new Object[n];
int j = 0;
do { a[j++] = p.item; } while ((p = p.next) != null && j < n);
current = p;
batch = j;
est = s - j;
return Spliterators.spliterator(a, 0, j, Spliterator.ORDERED);
}
return null;
}
public void forEachRemaining(Consumer<? super E> action) {
Node<E> p; int n;
if (action == null) throw new NullPointerException();
if ((n = getEst()) > 0 && (p = current) != null) {
current = null;
est = 0;
do {
E e = p.item;
p = p.next;
action.accept(e);
} while (p != null && --n > 0);
}
if (list.modCount != expectedModCount)
throw new ConcurrentModificationException();
}
public boolean tryAdvance(Consumer<? super E> action) {
Node<E> p;
if (action == null) throw new NullPointerException();
if (getEst() > 0 && (p = current) != null) {
--est;
E e = p.item;
current = p.next;
action.accept(e);
if (list.modCount != expectedModCount)
throw new ConcurrentModificationException();
return true;
}
return false;
}
public int characteristics() {
return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
}
}
}
從源碼理解LinkedList.java
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.