LinkedList全面說明:
LinkedList底層操作機制:
LinkedList的方法:
add():增加節點對象
remove():刪除一個節點對象(默認刪除第一個節點對象)
set():修改一個節點對象
get():得到一個節點對象
LinkedList的遍歷:
增強for循環
迭代器
普通for循化
LinkedList的源碼解讀:
增加源碼:
1. LinkedList linkedList = new LinkedList();
public LinkedList() {}
2. 這時 linkeList 的屬性 first = null last = null
3. 執行 添加
public boolean add(E e) {
linkLast(e);
return true;
}
4.將新的結點,加入到雙向鏈表的最后
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++;
}
刪除源碼:
1. 執行 removeFirst
public E remove() {
return removeFirst();
}
2. 執行
public E removeFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
3. 執行 unlinkFirst, 將 f 指向的雙向鏈表的第一個結點拿掉
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;
}