上面兩篇講了ArrayList和Vector,這一篇分析的是LinkedList ;一樣的 還是結合源碼(此處版本:jdk8)進行分析。
一 :數據結構
LinkedList底層是基於雙向鏈表實現,使用 Node 存儲鏈表節點信息。大概模型如下:
二 : 繼承關係
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
對比於List的另外兩個子類,其相同的點在於,LinkedList一樣實現 List 接口(能對它進行列表操作)、實現了Cloneable接口,即覆蓋了函數clone()以及實現了java.io.Serializable接口,(支持序列化,能通過序列化去傳輸);而不同的在於LinkedList繼承了AbstractSequentialList,而其他兩個繼承的是AbstractList;並且LinkedList不具備快速訪問能力;
LinkedList 是一個繼承於AbstractSequentialList的雙向鏈表。它也可以被當作堆棧、隊列或雙端隊列進行操作。
LinkedList 實現 Deque 接口,即能將LinkedList當作雙端隊列使用。
三:LinkedList的核心成員變量
直接附上源碼:
transient int size = 0;
transient Node<E> first;
transient Node<E> last;
其中,size是指當前包含的節點數;first是指向鏈表的第一個節點的引用,而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;
}
}
其中,item是當前節點值。next是指向後一個節點的引用,而perv指向前一節點;看到這裏應該會明白上面那張圖了。
四:構造函數
LinkedList有兩個構造函數,分別是:
/**
* 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);
}
正如註釋所講的那樣,無參構造實際上是構造一個空鏈表;而帶集合類的參數的構造則先構造一個空鏈表,然後利用迭代器進行插入操作,下面是其具體實現:
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;
}
addAll方法實際上是在index位置進行鏈表的插入操作;在代碼邏輯上,首先會進行一個標記它是在鏈表尾部還是中間部分進行插入;如果是尾部,那麼最後的last就指向包含集合類的最後一個元素的節點即可,如果是在中間部分,則需要對原來處於這個位置的節點的prev值進行修改。當然,如果是空鏈表的話,那麼還需要將first指向包含集合類中第一個元素的節點。
五:插入修改
linkFirst
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++;
}
這個方法實際上是將傳入的元素e鏈接成爲首節點,代碼邏輯上是新建一個節點,把這個節點的next指向原來的first指向的節點,然後把first指向這個節點;最後把原來的first指向的節點的前驅修改爲這個新節點(若之前爲空鏈表則把last也指向這個新節點即可)
linkLast
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++;
}
這個方法和上面的linkFirst很相似,實際上是將傳入的元素e鏈接成爲末節點,代碼邏輯上一樣是新建一個節點,把這個節點的前驅指向原來的last指向的節點,然後把last指向這個節點;最後把原來的末節點的後繼修改爲這個新節點(若之前爲空鏈表則把first也指向這個新節點即可)
linkBefore
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++;
}
linkBefore實際上是在某個非空節點succ之前去插入一個節點,實現過程如下:新建一個節點,把這個節點的前驅指向succ原本的前驅,把這個節點的後繼指向succ,然後再去修改原來succ的前驅節點的後繼指向以及succ的前驅指向。
add
public boolean add(E e) {
linkLast(e);
return true;
}
public void add(int index, E element) {
checkPositionIndex(index);
if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}
源碼可以看到,LinkedList兩個add方法的區別在於一個是沒有指明位置默認放到鏈表最後,實際上的實現還是去調用linkLast()和linkBefore()這兩個方法
set
public E set(int index, E element) {
checkElementIndex(index);
Node<E> x = node(index);
E oldVal = x.item;
x.item = element;
return oldVal;
}
這個方法其是將index處的節點的item元素更換爲傳入的元素,最後再把原先的元素的值返回。
六:刪除
unlinkFirst
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;
}
這個方法是進行頭節點的刪除,代碼邏輯是先獲取first元素值,然後獲取first的next元素,接着將first節點指向next,再把原來的first節點的屬性值置爲null(包括item和next);如果next節點(原first節點的nex節點)爲null,則將last置爲null值;如果不爲null,則將next節點的prev屬性置爲null;
最後修正元素個數以及修改次數(size和modCount)。
unlinkLast
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;
}
這個方法是進行尾節點的刪除,代碼邏輯是先獲取last元素值,然後獲取last的prev元素,接着將last節點指向prev,再原來的last節點的屬性值置爲null(包括item和prev);如果prev節點爲null,則將first置爲null值;如果不爲null,則將prev節點的next屬性置爲null;
最後修正元素個數以及修改次數(size和modCount)。
unlink
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;
}
這個方法是對某個指定節點的刪除,代碼邏輯是先獲取指定節點的所有元素值,然後看這個指定節點的前驅節點是否爲null,如果爲null則把first指向這個指定節點的後繼節點,如果不爲null,則修改前驅節點的next值並且把指定節點的prev值置爲null;接着看這個指定節點的後繼節點是否爲null。如果爲null則把last指向這個制定節點的前驅節點,如果不爲null,則修改這個後繼節點的prev值,並且把指定節點的next值置爲null;
最後把指定節點的item值置爲null並且修正元素個數以及修改次數(size和modCount)並將刪除的節點的元素值返回。
remove
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 E remove(int index) {
checkElementIndex(index);
return unlink(node(index));
}
public E remove() {
return removeFirst();
}
LinkedList的remove方法主要是上面這三個,分別是對移除指定元素,移除指定位置的元素以及默認移除,而默認的移除則是移除第一個元素,實際上還是通過removeFirst方法去實現的;而另外兩個移除方法則都是通過unlink方法去進行元素的移除
七:查詢搜索
getFirst
public E getFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
這個方法是進行頭節點的元素的獲取。
getLast
public E getLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}
這個方法是進行尾節點的元素的獲取。
get
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
這個方法是進行特定位置的節點的元素的獲取。
indexOf
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;
}
這個方法的作用是從頭結點開始尋找和傳入的元素相等的元素,如果找到了,則返回其在鏈表中的位置(下標);若沒找到,則返回-1;要注意的一點是,需要把情況分爲是null和不是null;因爲如果是null情況下還使用equals()方法會出現空指針異常。
lastIndex(Object o)
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;
}
這個方法的作用是從鏈表的尾節點至頭節點逆向搜索元素.
八、LinkedList的一些其他方法
contains
public boolean contains(Object o) {
return indexOf(o) != -1;
}
這個方法的作用是查看鏈表中是否含有某個元素,實際上還是通過indexOf來實現的
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;
x.next = null;
x.prev = null;
x = next;
}
first = last = null;
size = 0;
modCount++;
}
這個方法的作用是將鏈表清空
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;
}
}
這個方法的作用是返回指定位置的節點信息,LinkedList無法隨機訪問,只能通過遍歷的方式找到相應的節點,這裏爲了提高效率,把當前位置先和元素數量的中間位置開始判斷,小於中間位置則從頭節點開始遍歷,大於中間位置則從尾節點開始遍歷
九:隊列相關操作
//彈出第一個元素的值
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 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();
}
十:總結
1、不ArrayList和Vector繼承於 AbstractList, LinkedList繼承於 AbstractSequentialList;
2、ArrayList和Vector基於動態數組, LinkedList基於雙向鏈表;
3、對於隨機訪問,ArrayList 和Vector支持隨機訪問,LinkedList 不支持;但是LinkedList 在任意位置添加刪除元素更快;
4、LinkedList需要更多的內存,因爲ArrayList和Vector的每個索引的位置是實際的數據,而 LinkedList中的每個節點中存儲的是實際的數據和前後節點的位置;
5、ArrayList 和 LinkedList都是非同步的集合;
6、和ArrayList一樣,LinkedList也是非線程安全的,只有在單線程下才可以使用。
7、LinkedList沒有實現自己的 Iterator,使用的是 ListIterator
8、LinkedList是一個功能很強大的類,可以被當作List集合,雙端隊列和棧來使用