1. LinkedList的簡介 JDK 1.7
LinkedList是基于連結清單實作的,從源碼可以看出是一個雙向連結清單。除了當做連結清單使用外,它也可以被當作堆棧、隊列或雙端隊列進行操作。不是線程安全的,繼承AbstractSequentialList實作List、Deque、Cloneable、Serializable。
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
- LinkedList繼承AbstractSequentialList,AbstractSequentialList 實作了get(int index)、set(int index, E element)、add(int index, E element) 和 remove(int index)這些函數。這些接口都是随機通路List的。
- LinkedList 實作 List 接口,能對它進行隊列操作。
- LinkedList 實作 Deque 接口,即能将LinkedList當作雙端隊列使用。
- LinkedList 實作了Cloneable接口,即覆寫了函數clone(),能克隆。
- LinkedList 實作java.io.Serializable接口,這意味着LinkedList支援序列化,能通過序列化去傳輸。
2. LinkedList的繼承關系
LinkedList API
java.lang.Object
java.util.AbstractCollection<E>
java.util.AbstractList<E>
java.util.AbstractSequentialList<E>
java.util.LinkedList<E>
Type Parameters:
E - the type of elements held in this collection
All Implemented Interfaces:
Serializable, Cloneable, Iterable<E>, Collection<E>, Deque<E>, List<E>, Queue<E>
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsICdzFWRoRXdvN1LclHdpZXYyd2LcBzNvwVZ2x2bzNXak9CX90TQNNkRrFlQKBTSvwFbslmZvwFMwQzLcVmepNHdu9mZvwFVywUNMZTY18CX052bm9CX90TUOFTVE9EMZRUT4FEVkZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39TOzgDM1kDMyIDOyIDM3EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
3.LinkedList的API
boolean add(E object)
void add(int location, E object)
boolean addAll(Collection<? extends E> collection)
boolean addAll(int location, Collection<? extends E> collection)
void addFirst(E object)
void addLast(E object)
void clear()
Object clone()
boolean contains(Object object)
Iterator<E> descendingIterator()
E element()
E get(int location)
E getFirst()
E getLast()
int indexOf(Object object)
int lastIndexOf(Object object)
ListIterator<E> listIterator(int location)
boolean offer(E o)
boolean offerFirst(E e)
boolean offerLast(E e)
E peek()
E peekFirst()
E peekLast()
E poll()
E pollFirst()
E pollLast()
E pop()
void push(E e)
E remove()
E remove(int location)
boolean remove(Object object)
E removeFirst()
boolean removeFirstOccurrence(Object o)
E removeLast()
boolean removeLastOccurrence(Object o)
E set(int location, E object)
int size()
<T> T[] toArray(T[] contents)
Object[] toArray()
4.LinkedList源碼分析
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
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() {
}
/**
* 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
* c其元素将被放置到此清單中的集合
* @throws NullPointerException if the specified collection is null
*/
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
/**
* Links e as first element.
* e 作為第一個連結,私有方法,在addFirst(E e)方法中使用!
*/
private void linkFirst(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;
size++;
modCount++;
/*
/**
* 連結清單節點的構造函數。
* 參數說明:
* element —— 節點所包含的資料
* next —— 下一個節點
* prev —— 上一個節點
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
*/
}
/**
* Links e as last element.
* e 作為最後一個連結,私有方法,在addLast(E e)方法中使用!
*/
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++;
}
/**
* Inserts element e before non-null Node succ.
* 在非空節點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++;
}
/**
* Unlinks non-null first node f.
* 取消連結非空的第一個節點f。
* 私有方法,在removeFirst()方法中使用!
*/
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.
* 取消連結非空的最後一個節點l。
* 私有方法,在removeLast()方法中使用!
*/
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。
* 在remove中使用
*/
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;
}
/**
* 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)
throw new 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)
throw new NoSuchElementException();
return l.item;
}
/**
* 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)
throw new NoSuchElementException();
return unlinkFirst(f);
}
/**
* Removes and returns the last element from this list.
* 删除并傳回此清單中的最後一個元素。
* @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);
}
/**
* Inserts the specified element at the beginning of this list.
* 在此清單的開頭插入指定的元素。
* @param e the element to add
*/
public void addFirst(E e) {
linkFirst(e);
}
/**
* 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);
}
/**
*
*如果此清單包含指定的元素,則傳回true。 更正式地,當且僅當這個清單包含至少一個元素e使得
*(o == null?e == *null:o.equals(e))時,傳回true。
*
* @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; //使用indexOf 方法
}
/**
* Returns the number of elements in this list.
* 傳回此清單中的元素數。
* @return the number of elements in this list
*/
public int size() {
return size;
}
/**
* Appends the specified element to the end of this list.
* 将指定的元素追加到此清單的末尾。
* <p>This method is equivalent to {@link #addLast}.
* 此方法等效與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;
}
/**
*
*從清單中删除指定元素的第一次出現(如果存在)。 如果此清單不包含元素,則不會更改。
*
*更正式地,删除具有最低索引i的元素,使得(如果這樣的元素存在)(o == null?get(i)== null:o.equals(get(i)))。 *如果此清單包含指定的元素(或等效地,如果此清單作為調用的結果更改),則傳回true。
*
* @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) { //從頭開始周遊整個清單,若清單中有null的元素,則移除!(第一次出現)
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {//從頭開始周遊整個清單,若清單中有 o 的元素,則移除!(第一次出現)
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) {
return addAll(size, 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); //檢查索引位置是否有效 index >= 0 && index <= size 傳回true。
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;
}
/**
* Removes all of the elements from this list.
* The list will be empty after this call returns.
*從此清單中删除所有元素。 此調用傳回後,清單将為空。
*/
public void clear() {
// Clearing all of the links between nodes is "unnecessary", but:
// - helps a generational GC if the discarded nodes inhabit
// more than one generation
// - is sure to free memory even if there is a reachable Iterator
for (Node<E> x = first; x != null; ) {
Node<E> next = x.next;
x.item = null; //設定為null ,等待gc回收
x.next = null; //設定為null ,等待gc回收
x.prev = null; //設定為null ,等待gc回收
x = next;
}
first = last = null;
size = 0; //設定清單的大小為 0;
modCount++;
}
// Positional Access Operations
// 定位通路操作
/**
* Returns the element at the specified position in this list.
* 傳回此lis中指定位置的元素
* @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 >= 0 && index <= size 傳回true。
return node(index).item; //傳回指定元素索引處的(非空)節點的元素(data)
}
/**
* 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 >= 0 && index <= size 傳回true。
Node<E> x = node(index); //傳回指定元素索引處的(非空)節點。
//替換操作
E oldVal = x.item;
x.item = element;
return oldVal;
}
/**
* 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}
*/
public void add(int index, E element) {
checkPositionIndex(index);
if (index == size) //索引位置等于 清單的大小,則在連結清單後面添加元素
linkLast(element);
else
linkBefore(element, node(index)); //否則在連結清單中間插入元素
}
/**
* 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.
*
* 删除此清單中指定位置的元素。 将任何後續元素向左移(從它們的索引中減去一個)。
* 傳回從清單中删除的元素。
*
* @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)); // node(index)擷取指定索引的節點。unlink()移除節點資料,并将任何後續元素向左移
}
/**
* 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.
* 構造一個IndexOutOfBoundsException詳細消息。
*/
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));
}
/**
* Returns the (non-null) Node at the specified element index.
* 傳回指定元素索引處的(非空)節點。
*/
Node<E> node(int index) {
// assert isElementIndex(index);
if (index < (size >> 1)) {
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
Node<E> x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
// Search Operations
// 搜尋操作
/**
* Returns the index of the first occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the lowest index {@code i} such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*
* 傳回此清單中指定元素的第一次出現的索引,如果此清單不包含元素,則傳回-1。
* 更正式地,傳回最低索引i,使得(o == null?get(i)== null:o.equals(get(i))),
* 或-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 {//從 頭部 開始周遊整個連結清單
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item))
return index;
index++;
}
}
return -1;
}
/**
* Returns the index of the last occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the highest index {@code i} such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*
* 傳回此清單中指定元素的最後一次出現的索引,如果此清單不包含元素,則傳回-1。
* 更正式地,傳回最高索引i,使得(o == null?get(i)== null:o.equals(get(i))),
* 或-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) {
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;
}
// Queue operations.
// 隊列操作。
/**
* Retrieves, but does not remove, the head (first element) of this list.
* 檢索,但不删除此清單的頭(第一個元素)。
* @return the head of this list, or {@code null} if this list is empty
* 傳回 此清單的頭部,或null(如果此清單為空)
* @since 1.5
*/
public E peek() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
/**
* 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();
}
/**
* Retrieves and removes the head (first element) of this list.
* 檢索并删除此清單的頭(第一個元素)。
* @return the head of this list, or {@code null} if this list is empty
* 傳回 : 此清單的頭部,或 null(如果此清單為空)
* @since 1.5
*/
public E poll() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
/**
* 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();
}
/**
* 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
*/
public boolean offer(E e) {
return add(e);
}
// Deque operations
// Deque操作
/**
* 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
*/
public boolean offerFirst(E e) {
addFirst(e);
return true;
}
/**
* 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
*/
public boolean offerLast(E e) {
addLast(e);
return true;
}
/**
* Retrieves, but does not remove, the first element of this list,
* or returns {@code null} if this list is empty.
* 檢索但不删除此清單的第一個元素,如果此清單為空,則傳回null
* @return the first element of this list, or {@code null}
* if this list is empty
* @since 1.6
*/
public E peekFirst() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
/**
* Retrieves, but does not remove, the last element of this list,
* or returns {@code null} if this list is empty.
* 檢索但不删除此清單的最後一個元素,如果此清單為空,則傳回null
* @return the last element of this list, or {@code null}
* if this list is empty
* @since 1.6
*/
public E peekLast() {
final Node<E> l = last;
return (l == null) ? null : l.item;
}
/**
* Retrieves and removes the first element of this list,
* or returns {@code null} if this list is empty.
*
* 檢索并删除此清單的第一個元素,如果此清單為空,則傳回null
*
* @return the first element of this list, or {@code null} if
* this list is empty
* @since 1.6
*/
public E pollFirst() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
/**
* Retrieves and removes the last element of this list,
* or returns {@code null} if this list is empty.
*
*檢索并删除此清單的最後一個元素,如果此清單為空,則傳回null
*
* @return the last element of this list, or {@code null} if
* this list is empty
* @since 1.6
*/
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.
* 将元素推送到此清單所表示的堆棧。
* 換句話說,将元素插入此清單的前面。(棧push 元素存放在棧頂)
* <p>This method is equivalent to {@link #addFirst}.
* 這個方法等效于addFirst方法
* @param e the element to push
* @since 1.6
*/
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()}.
* 此方法 相當于 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();
}
/**
*删除此清單中指定元素的第一次出現(從頭到尾周遊清單時)。
*如果清單不包含元素,則不會更改。
* @param o element to be removed from this list, if present
* @return {@code true} if the list contained the specified element
* @since 1.6
*/
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
* @since 1.6
*/
//從連結清單尾部開始周遊,找到元素移除
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;
}
}
}
return false;
}
/**
*傳回此清單中的元素(按正确順序)的清單疊代器,從清單中指定的位置開始。
* 服從List.listIterator(int)的約定。
*/
public ListIterator<E> listIterator(int index) {
checkPositionIndex(index);
return new ListItr(index);
}
private class ListItr implements ListIterator<E> {
//不去分析這個方法中的内容,有需要的請自行分析
}
private static class Node<E> {
E item; // 目前節點所包含的值
Node<E> next;// 下一個節點
Node<E> prev; // 上一個節點
/**
* 連結清單節點的構造函數。
* 參數說明:
* element —— 節點所包含的資料
* next —— 下一個節點
* previous —— 上一個節點
*/
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
/**
* @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();
}
}
/**
* 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;
}
/**
*以正确的順序傳回包含此清單中所有元素的數組(從第一個元素到最後一個元素)。
*/
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;
}
/**
*傳回一個包含正确順序(從第一個元素到最後一個元素)的清單中所有元素的數組。
*/
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
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).
*
* 将LinkedList執行個體的狀态儲存到流(即,序列化它)。
*
*/
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).
* 從流重構 LinkedList 執行個體(即,反序列化它)
*/
@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());
}
}
5.總結
1:LinkedList的實作是基于雙向循環連結清單,實作的 List和Deque 接口。實作所有可選的清單操作,并允許所有元素(包括null)。
2:LinkedList是非線程安全的,隻在單線程下适合使用。
3:這個類的iterator和傳回的疊代器listIterator方法是fail-fast ,要注意ConcurrentModificationException 。
4:LinkedList實作了Serializable接口,是以它支援序列化,能夠通過序列化傳輸,實作了Cloneable接口,能被克隆。
5:在查找和删除某元素時,都分為該元素為null和不為null兩種情況來處理,LinkedList中允許元素為null。
6:由于是基于清單的,LinkedList的沒有擴容方法!預設加入元素是尾部自動擴容!
7:LinkedList還實作了棧和隊列的操作方法,是以也可以作為棧、隊列和雙端隊列來使用,如peek 、push、pop等方法。
8:LinkedList是基于連結清單實作的,是以插入删除效率高,查找效率低!(因為查找需要周遊整個連結清單)
9:1.6 使用的是Entry存儲
// 雙向連結清單的節點所對應的資料結構。
// 包含3部分:上一節點,下一節點,目前節點值。
private static class Entry<E> {
E element; // 目前節點所包含的值
Entry<E> next; // 下一個節點
Entry<E> previous; // 上一個節點
/**
* 連結清單節點的構造函數。
* 參數說明:
* element —— 節點所包含的資料
* next —— 下一個節點
* previous —— 上一個節點
*/
Entry(E element, Entry<E> next, Entry<E> previous) {
this.element = element;
this.next = next;
this.previous = previous;
}
}
1.7使用的是Node存儲
// 雙向連結清單的節點所對應的資料結構。
// 包含3部分:上一節點,下一節點,目前節點值。
private static class Node<E> {
E item; // 目前節點所包含的值
Node<E> next;// 下一個節點
Node<E> prev; // 上一個節點
/**
* 連結清單節點的構造函數。
* 參數說明:
* element —— 節點所包含的資料
* next —— 下一個節點
* previous —— 上一個節點
*/
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
歡迎通路我的csdn部落格,我們一同成長!
"不管做什麼,隻要堅持下去就會看到不一樣!在路上,不卑不亢!"
部落格首頁:http://blog.csdn.net/u010648555
轉載于:https://www.cnblogs.com/aflyun/p/6481274.html