LinkedList
LinkedList是一種可以在任何位置進行高效地插入和刪除操作的有序序列。
它的最基本存儲結構是一個節點:每個節點將存儲對象,以及前后節點的引用。
結構圖

從上面的結構圖中,我們可以了解到 ListedList 底層是基于雙向鏈表實現的。
圍起來的可以看成 LinkedList 類,它定義了三個 transient 成員變量:first、last、size。這三個變量是整個 LinkedList 類的關鍵點。
源碼分析
add(E e) 源碼分析
/**
* Appends the specified element to the end of this list.
*
* <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;
}
/**
* Links e as last element.
*/
void linkLast(E e) {
final Node<E> l = last; // 將當前最后一個元素寄存在 l
final Node<E> newNode = new Node<>(l, e, null); // new 一個新節點:pre的引用為l;存儲元素為e;next的引用為null
last = newNode; // 將新節點引用覆蓋成員變量 last
if (l == null)
first = newNode; // 若l為null,說明之前鏈表為空,此時新節點為首個元素
else
l.next = newNode; // 否則,更新l的next引用
size++; // size+1
modCount++; // 非查詢操作 modCount 都會 +1
}
add(int index, E element) 方法分析
/**
* 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); // 檢查 index 是否大于 size
if (index == size)
linkLast(element); // 直接在鏈表末尾追加
else
linkBefore(element, node(index)); // 插入index 節點前面
}
// 檢查 index 是否超出范圍 超出則拋出 IndexOutOfBoundsException
private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* 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;
}
/**
* 根據 index 查找 node
* 該方法利用了雙向鏈表的特性,index 距離哪個鏈表頭近就從哪邊開始開始遍歷
* 時間復雜度為 O(n/2);
* 當 index 接近 size 的中間值時,效率最低
* Returns the (non-null) Node at the specified element index.
*/
Node<E> node(int index) {
// assert isElementIndex(index);
if (index < (size >> 1)) { // size 右移一位(除以2)
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;
}
}
優缺點
優點
增刪元素效率高(只需要更新節點附近的引用即可)
缺點
由于查詢需要進行遍歷,因此效率低
知識腦圖

以上所述是小編給大家介紹的Java 集合系列(三)—— LinkedList詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對億速云網站的支持!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。