java原始碼品讀(13)— LinkedList
概述
之前說過了LinkedList的相關的父類,今天我們來看看LinkedList本身的內容。 眾所周知,ArrayList和LinkedList是我們工作中經常用到的兩種集合,這兩兄弟也經常會被拿到一起來做比較,ArrayList因其底層的陣列結構,所以其改和查的效率相當高,但是增和刪的效率就相對較低,而LinkedList則正好相反,增和刪都因其底層的鏈式結構,效率很高,而改和查就需要先定位到目標的節點,所以效率較低。 至於細節的東西到底是什麼,我們就要從它的原始碼中一點一點去摸索。
- 成員屬性
//集合大小 transient int size = 0; //集合中連結串列的第一個節點 transient Node<E> first; //集合中連結串列的最後一個節點 transient Node<E> last;
三者都使用transient關鍵字修飾,套路跟之前我們看過的ArrayList一致,由本類中的私有方法writeObject和readObject提供序列化的支援,同時省去三個屬性在序列化時佔用的空間。
- 構造方法
public LinkedList() {
}
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
提供兩個構造器,一個無參構造器和一個有參構造器,有參構造器需要傳入一個集合,將集合中的元素加入LinkedList中,如果集合為空的話,會丟擲異常。
- 內部類
LinkedList中包含幾個內部類ListItr(LinkedList的迭代器)、Node(LinkedList用於儲存元素的節點)、DescendingIterator(LinkedList的倒序迭代器)、LLSpliterator(LinkedList的並行迭代器) 三個迭代器在這裡就不細說了,跟ArrayList的套路大致相同,只是其中的有些方法使用的是LinkedList中的相應方法。這個如果有同學不清楚的話可以移步 ArrayList迭代器 和 ArrayList並行迭代器 細細理解。
下面我們來看一下LinkedList中比較重要的一個內部類: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; } }
節點的設計相對簡單但是也實用,滿足雙向連結串列的資料儲存要求。
- 成員方法
//將指定元素連結為頭元素
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++;
}
//將指定元素連結為尾元素
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++;
}
//在指定節點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++;
}
//將頭元素取出並返回(需要保證指定元素跟頭元素相等且不為null)
private E unlinkFirst(Node<E> f) {
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;
}
//將尾元素取出並返回(需要保證指定元素跟尾元素相等且不為null)
private E unlinkLast(Node<E> l) {
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;
}
//取出指定元素(需要保證指定元素不為null)
E unlink(Node<E> x) {
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;
}
//獲取頭元素
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 boolean contains(Object o) {
return indexOf(o) != -1;
}
//集合大小
public int size() {
return size;
}
//尾部增加指定元素
public boolean add(E e) {
linkLast(e);
return true;
}
//刪除指定元素在集合中第一個例項
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;
}
//尾部增加指定集合的所有元素
public boolean addAll(Collection<? extends E> c) {
return addAll(size, c);
}
//從指定位置開始增加集合中的所有元素
public boolean addAll(int index, Collection<? extends E> c) {
checkPositionIndex(index);
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;
}
//清空所有元素
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 = last = null;
size = 0;
modCount++;
}
//獲取指定位置元素
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));
}
//檢視指定位置是否有元素(根據索引)
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}
//檢視指定位置是否有元素(根據位置)
private boolean isPositionIndex(int index) {
return index >= 0 && index <= size;
}
//陣列越界錯誤資訊
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 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;
}
//獲取指定元素最後一次出現的索引
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;
}
//返回列表的頭元素,但是不會刪除列表中的頭元素(無異常)
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);
}
//頭部新增一個元素
public boolean offerFirst(E e) {
addFirst(e);
return true;
}
//尾部新增一個元素
public boolean offerLast(E e) {
addLast(e);
return true;
}
//返回頭元素
public E peekFirst() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
//返回尾元素
public E peekLast() {
final Node<E> l = last;
return (l == null) ? null : l.item;
}
//取出並返回頭元素
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);
}
//頭部新增一個元素
public void push(E e) {
addFirst(e);
}
//取出並返回頭元素,無頭元素會丟擲異常
public E pop() {
return removeFirst();
}
//移除第一個出現的指定元素
public boolean removeFirstOccurrence(Object o) {
return remove(o);
}
//移除最後一次出現的指定元素
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;
}
//獲取一個從指定下標開始的迭代器
public ListIterator<E> listIterator(int index) {
checkPositionIndex(index);
return new ListItr(index);
}
//獲取一個倒序的迭代器
public Iterator<E> descendingIterator() {
return new DescendingIterator();
}
//使用Object的克隆方法進行復制
@SuppressWarnings("unchecked")
private LinkedList<E> superClone() {
try {
return (LinkedList<E>) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
//自己的克隆方法,元素相同,修改次數重新計算
public Object clone() {
LinkedList<E> clone = superClone();
clone.first = clone.last = null;
clone.size = 0;
clone.modCount = 0;
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;
}
- 方法總結
LinkedList中存在很多相似的方法,在上面的原始碼中我們大致可以總結出下面的這些東西,以方便以後的使用
增加方法 | 獲取方法 | 刪除方法 | 備註 |
---|---|---|---|
add(E),addFirst(E),addLast(E) | get(index),getFirst(),getLast() | remove(E),removeFirst(),removeLast() | 獲取刪除集合中無元素會丟擲異常 |
push(),offer(E),offerFirst(E),offerLast(E) | peek(),peekFirst(),peekLast() | pop(),poll(),pollFirst(),pollLast() | 獲取刪除集合中無元素返回null |
隨機訪問慢的原因:
Node<E> node(int 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;
}
}
查詢指定位置的節點時,根據索引的位置進行正向或者是逆向的迴圈,只到找到相應的節點。而不是像ArrayList一樣直接就能找到相應的位置。 新增和刪除的操作,都是在佇列的首尾進行,所以相當的省力,而ArrayList的刪除和新增不僅僅需要找到指定的位置,而且還夾雜著一些元素移位的操作,所以就相對耗時較長。