Doubly-linked list implementation of the List and Deque interfaces. Implements all optional list operations, and permits all elements (including null).
LinkedList實現了list接口,其底層實際上一個雙向鏈表,其基本操作就是對雙向鏈表的操作。當然,LinkedList是允許添加null的。
簡單例子如下:
public class TestLinkList {
public static void main(String[] args) {
List<String> list=new LinkedList<String>();
list.add("A");
list.add("B");
list.add(null);
list.add("C");
}
}
可以查看,鏈表持有一個first與last節點,分別指向第一個和最後一個節點。對於每個具體的節點,其有next與prev屬性,分別指向其下一個節點和上一個節點。
其數據結構圖如下:
開始的一個第一個節點爲空節點,不保存數據。
LinkedList部分源碼:
/**
* Pointer to first node.
* Invariant: (first == null && last == null) ||
* (first.prev == null && first.item != null)
*/
//指向第一個節點
transient Node<E> first;
/**
* Pointer to last node.
* Invariant: (first == null && last == null) ||
* (last.next == null && last.item != null)
*/
//指向最後一個節點
transient Node<E> last;
//節點
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;
}
}
//鏈表的最後添加節點
public boolean add(E e) {
linkLast(e);
return true;
}
//獲取指定位置的節點
public E get(int index) {
//下標越界檢查
checkElementIndex(index);
//獲取指定位置的數據
return node(index).item;
}
Node<E> node(int index) {
//如果要獲取的下標在size/2之前,則從前往後遍歷
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 是一個實現了list接口,底層是一個雙向鏈表,基本的操作就是對鏈表的操作, 因爲是基於鏈表來實現的,所以其容量是無限的, 在get操作的時候,會判斷index與鏈表一般的大小,若index小於size/2,則從表頭來開始查找,否則從鏈表的尾部開始查找