LinkedList底層是鏈表結構
public E removeFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
first指向鏈表中的第一個結點,那麼接下來看看unlinkFirst(f)方法實現:
先看一下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:當前結點的下一個結點;prev:當前結點的前一個結點
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;
//判斷,如果沒有下一個結點,那麼最後一個結點就不存在,null
if (next == null)
last = null;
else
//此處的next.prev即第一個結點,要刪除,所以賦值爲null
next.prev = null;
//鏈表大小減一
size--;
modCount++;
//將要刪除的元素返回
return element;
}
如有不當之處,還望賜教!