本系列:
給jdk寫註釋系列之jdk1.6容器(1)-ArrayList源碼解析
LinkedList是基於鏈表結構的一種List,在分析LinkedList源碼前有必要對鏈表結構進行說明。
2.定義
1
2
3
|
public
class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, java.io.Serializable |
可以看出LinkedList 繼承AbstractSequentialList 抽象類,實現了List,Deque,Cloneable,Serializable 幾個接口,AbstractSequentialList 繼承 AbstractList,是對其中方法的再抽象,其主要作用是最大限度地減少了實現受“連續訪問”數據存儲(如鏈接列表)支持的此接口所需的工作,簡單說就是,如果需要快速的添加刪除數據等,用AbstractSequentialList抽象類,若是需要快速隨機的訪問數據等用AbstractList抽象類(詳細說明會在iterator 分析中進行解釋)。
public interface Deque<E> extends Queue<E> {
void addFirst(E e);
boolean offerFirst(E e);
boolean offerLast(E e);
E removeFirst();
E removeLast();
E pollFirst();
E pollLast();
E getFirst();
E getLast();
E peekFirst();
E peekLast();
boolean removeFirstOccurrence(Object o);
boolean removeLastOccurrence(Object o);
// *** Queue methods ***
boolean add(E e);
boolean offer(E e);
E remove();
E poll();
E element();
E peek();
// *** Stack methods ***
void push(E e);
E pop();
// *** Collection methods ***
boolean remove(Object o);
boolean contains(Object o);
public int size();
Iterator<E> iterator();
Iterator<E> descendingIterator();
}
3.底層存儲
1
2
|
private
transient Entry<E> header = new Entry<E>( null , null ,
null ); private
transient int size = 0 ; |
LinkedList中提供了上面兩個屬性,其中size和ArrayList中一樣用來計數,表示list的元素數量,而header則是鏈表的頭結點,Entry則是鏈表的節點對象。
private static class Entry<E> { E element; // 當前存儲元素 Entry<E> next; // 下一個元素節點 Entry<E> previous; // 上一個元素節點 Entry(E element, Entry<E> next, Entry<E> previous) { this.element = element; this.next = next; this.previous = previous; } }
/**
* 構造一個空的LinkedList .
*/
public LinkedList() {
//將header節點的前一節點和後一節點都設置爲自身
header.next = header. previous = header ;
}
/**
* 構造一個包含指定 collection 中的元素的列表,這些元素按其 collection 的迭代器返回的順序排列
*/
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
public LinkedList() {
header.next = null;
header. previous = null;
}
/**
* 將一個元素添加至list尾部
*/
public boolean add(E e) {
// 在header前添加元素e,header前就是最後一個結點啦,就是在最後一個結點的後面添加元素e
addBefore(e, header);
return true;
}
/**
* 在指定位置添加元素
*/
public void add(int index, E element) {
// 如果index等於list元素個數,則在隊尾添加元素(header之前),否則在index節點前添加元素
addBefore(element, (index== size ? header : entry(index)));
}
private Entry<E> addBefore(E e, Entry<E> entry) {
// 用entry創建一個要添加的新節點,next爲entry,previous爲entry.previous,意思就是新節點插入entry前面,確定自身的前後引用,
Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);
// 下面修改newEntry的前後節點的引用,確保其鏈表的引用關係是正確的
// 將上一個節點的next指向自己
newEntry. previous.next = newEntry;
// 將下一個節點的previous指向自己
newEntry. next.previous = newEntry;
// 計數+1
size++;
modCount++;
return newEntry;
/**
* 添加一個集合元素到list中
*/
public boolean addAll(Collection<? extends E> c) {
// 將集合元素添加到list最後的尾部
return addAll(size , c);
}
/**
* 在指定位置添加一個集合元素到list中
*/
public boolean addAll(int index, Collection<? extends E> c) {
// 越界檢查
if (index < 0 || index > size)
throw new IndexOutOfBoundsException( "Index: "+index+
", Size: "+size );
Object[] a = c.toArray();
// 要插入元素的個數
int numNew = a.length ;
if (numNew==0)
return false;
modCount++;
// 找出要插入元素的前後節點
// 獲取要插入index位置的下一個節點,如果index正好是lsit尾部的位置那麼下一個節點就是header,否則需要查找index位置的節點
Entry<E> successor = (index== size ? header : entry(index));
// 獲取要插入index位置的上一個節點,因爲是插入,所以上一個點擊就是未插入前下一個節點的上一個
Entry<E> predecessor = successor. previous;
// 循環插入
for (int i=0; i<numNew; i++) {
// 構造一個節點,確認自身的前後引用
Entry<E> e = new Entry<E>((E)a[i], successor, predecessor);
// 將插入位置上一個節點的下一個元素引用指向當前元素(這裏不修改下一個節點的上一個元素引用,是因爲下一個節點隨着循環一直在變)
predecessor. next = e;
// 最後修改插入位置的上一個節點爲自身,這裏主要是爲了下次遍歷後續元素插入在當前節點的後面,確保這些元素本身的順序
predecessor = e;
}
// 遍歷完所有元素,最後修改下一個節點的上一個元素引用爲遍歷的最後一個元素
successor. previous = predecessor;
// 修改計數器
size += numNew;
return true;
}
/**
* 刪除第一個匹配的指定元素
*/
public boolean remove(Object o) {
// 遍歷鏈表找到要被刪除的節點
if (o==null) {
for (Entry<E> e = header .next; e != header; e = e.next ) {
if (e.element ==null) {
remove(e);
return true;
}
}
} else {
for (Entry<E> e = header .next; e != header; e = e.next ) {
if (o.equals(e.element )) {
remove(e);
return true;
}
}
}
return false;
}
private E remove(Entry<E> e) {
if (e == header )
throw new NoSuchElementException();
// 被刪除的元素,供返回
E result = e. element;
// 下面修正前後對該節點的引用
// 將該節點的上一個節點的next指向該節點的下一個節點
e. previous.next = e.next;
// 將該節點的下一個節點的previous指向該節點的上一個節點
e. next.previous = e.previous;
// 修正該節點自身的前後引用
e. next = e.previous = null;
// 將自身置空,讓gc可以儘快回收
e. element = null;
// 計數器減一
size--;
modCount++;
return result;
}
上面對於鏈表增加元素總結了,一句話就是“改變前後的互相指向關係”,刪除也是同樣的道理,由於節點被刪除,該節點的上一個節點和下一個節點互相拉一下小手就可以了,注意的是“互相”,不能一廂情願。
/**
* 修改指定位置索引位置的元素
*/
public E set( int index, E element) {
// 查找index位置的節點
Entry<E> e = entry(index);
// 取出該節點的元素,供返回使用
E oldVal = e. element;
// 用新元素替換舊元素
e. element = element;
// 返回舊元素
return oldVal;
}
/**
* 查找指定索引位置的元素
*/
public E get( int index) {
return entry(index).element ;
}
/**
* 返回指定索引位置的節點
*/
private Entry<E> entry( int index) {
// 越界檢查
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException( "Index: "+index+
", Size: "+size );
// 取出頭結點
Entry<E> e = header;
// size>>1右移一位代表除以2,這裏使用簡單的二分方法,判斷index與list的中間位置的距離
if (index < (size >> 1)) {
// 如果index距離list中間位置較近,則從頭部向後遍歷(next)
for (int i = 0; i <= index; i++)
e = e. next;
} else {
// 如果index距離list中間位置較遠,則從頭部向前遍歷(previous)
for (int i = size; i > index; i--)
e = e. previous;
}
return e;
}
/**
* Returns <tt>true</tt> if this list contains the specified element.
* More formally, returns <tt>true</tt> if and only if this list contains
* at least one element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.
*
* @param o element whose presence in this list is to be tested
* @return <tt> true</tt> if this list contains the specified element
*/
public boolean contains(Object o) {
return indexOf(o) != -1;
}
/**
* Returns the index of the first occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the lowest index <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*
* @param o element to search for
* @return the index of the first occurrence of the specified element in
* this list, or -1 if this list does not contain the element
*/
public int indexOf(Object o) {
int index = 0;
if (o==null) {
for (Entry e = header .next; e != header; e = e.next ) {
if (e.element ==null)
return index;
index++;
}
} else {
for (Entry e = header .next; e != header; e = e.next ) {
if (o.equals(e.element ))
return index;
index++;
}
}
return -1;
}
/**
* Returns the index of the last occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the highest index <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*
* @param o element to search for
* @return the index of the last occurrence of the specified element in
* this list, or -1 if this list does not contain the element
*/
public int lastIndexOf(Object o) {
int index = size ;
if (o==null) {
for (Entry e = header .previous; e != header; e = e.previous ) {
index--;
if (e.element ==null)
return index;
}
} else {
for (Entry e = header .previous; e != header; e = e.previous ) {
index--;
if (o.equals(e.element ))
return index;
}
}
return -1;
}
/**
* Returns the number of elements in this list.
*
* @return the number of elements in this list
*/
public int size() {
return size ;
}
/**
* {@inheritDoc}
*
* <p>This implementation returns <tt>size() == 0 </tt>.
*/
public boolean isEmpty() {
return size() == 0;
}
/**
* Adds the specified element as the tail (last element) of this list.
*
* @param e the element to add
* @return <tt> true</tt> (as specified by {@link Queue#offer})
* @since 1.5
*/
public boolean offer(E e) {
return add(e);
}
/**
* Retrieves and removes the head (first element) of this list
* @return the head of this list, or <tt>null </tt> if this list is empty
* @since 1.5
*/
public E poll() {
if (size ==0)
return null;
return removeFirst();
}
/**
* Removes and returns the first element from this list.
*
* @return the first element from this list
* @throws NoSuchElementException if this list is empty
*/
public E removeFirst() {
return remove(header .next);
}
/**
* Retrieves, but does not remove, the head (first element) of this list.
* @return the head of this list, or <tt>null </tt> if this list is empty
* @since 1.5
*/
public E peek() {
if (size ==0)
return null;
return getFirst();
}
/**
* Returns the first element in this list.
*
* @return the first element in this list
* @throws NoSuchElementException if this list is empty
*/
public E getFirst() {
if (size ==0)
throw new NoSuchElementException();
return header .next. element;
}
/**
* Pushes an element onto the stack represented by this list. In other
* words, inserts the element at the front of this list.
*
* <p>This method is equivalent to {@link #addFirst}.
*
* @param e the element to push
* @since 1.6
*/
public void push(E e) {
addFirst(e);
}
/**
* Inserts the specified element at the beginning of this list.
*
* @param e the element to add
*/
public void addFirst(E e) {
addBefore(e, header.next );
}