1. 程式人生 > >基於JDK1.8的LinkedList原始碼學習筆記

基於JDK1.8的LinkedList原始碼學習筆記

        LinkedList作為一種常用的List,是除了ArrayList之外最有用的List。其同樣實現了List介面,但是除此之外它同樣實現了Deque介面,而Deque是一個雙端佇列介面,其繼承自Queue,所以LinkedList同樣可以用來模擬佇列,棧以及雙端佇列。

圖片1

一.基本用法

      因為LinkedList是基於連結串列實現的,所以註定其插入和刪除操作速度要快於ArrayList,但是由於其是連結串列結構,所以其隨機訪問查詢檢索速度慢於基於陣列的ArrayList。

         這裡先主要說一下LinkedList的基本用法,以及模擬佇列,模擬棧,模擬雙端佇列的常用方法。

1.LinkedList,List用法

List<String> myList=new LinkedList<String>();
(1)//增加元素
String s="myString"
myList.add(s);//這裡等同於在連結串列尾端增加元素addLast(e)
myList.add(1,s);//在指定位置插入元素

2)//獲取指定位置的元素
String getString=myList.get(10)//獲取連結串列第11處元素,從頭計算

3)//刪除元素
myList.remove(2)//刪除連結串列第3個元素

4)//clear清空連結串列
myList.clear() (5)isEmpty(),//判斷list是否為空

2.LinkedList模擬佇列

Queue<String> myQueue=new LinkedList<String>();
(1)//新增元素到到隊尾
   myQueue.offer(myString);
   myQueue.add(myString);

(2)檢索但不刪除隊首元素
    String head=myQueue.peek();//若為空,返回null
    String head=myQueue.element();//若佇列為空,丟擲NoSuchElementException
(3)取出並且刪除隊首元素 String head=myQueue.poll(); //若為空,返回null String head=myQueue.remove();//若佇列為空,丟擲NoSuchElementException //綜上,LinkedList通過在連結串列尾插入元素,連結串列首取出元素,模擬了先進先出FIFO的佇列,但是 //這裡的佇列是單向的

3.LinkedList模擬棧Stack操作

Deque<String> stack=new LinkedList<String>();
//(1)進棧操作    
    stack.push(myString);

//(2)出棧操作,刪除並且取出
    stack.pop();
//(3)若是檢索不刪除則還用peek
    stack.peek();
//LinkedList通過在隊首插入元素,隊首取出元素,模擬stack的先進後出操作

4.LinkedList模擬雙端佇列Deque操作

Deque<String> deque=new LinkedList<String>();
//(1)隊首新增元素
  deque.offerFirst(myString);
  deque.addFirst(myString);
//(2)隊尾新增元素
  deque.offerLast(myString);
  deque.addLast(myString);

//(3)檢索但不刪除隊首元素
   String first=deque.peekFirst();
   first=deque.getFirst();
//(4)檢索但不刪除隊尾元素
    String last=deque.peekLast();
    last=deque.getLast();

//(5)取出並刪除隊首元素
    deque.pollFirst();
   deque.removeFirst();
//(6)取出並刪除隊尾元素
   deque.pollLast();
   deque.removeLast();

//這樣LinkedList通過操作連結串列隊首隊尾就實現了雙端佇列

5.LinkedList迭代遍歷

//(1)for each 迴圈
List<String> list=new ArrayList<String>();
for(String s:list){
////
}

//(2)iterator迭代器
Iterator<String> it=list.iterator();
while(it.hasNext()){
   it.next();
}

//(3)同時List還提供了ListIterator介面,擁有反向正向迭代

ListIterator<String> lit=list.listIterator();
while(lit.hasNext()){
   it.next();
}//正向迭代

while(it.hasPrevious()){
   it.previous();
}//反向迭代

//值得注意的是,以前可能忽視了,listIterator迭代器同時提供了增刪改的功能
//add(),在指定位置插入一個元素,當前迭代的前面插入
//set(E,e),修改當前迭代為指定元素
//remove();刪除上一次迭代

二.JDK原始碼分析

   這裡的JDK是基於JDK1.8的原始碼。

1.定義,LinkedList類定義

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
 // 繼承了AbstractSequentialList抽象類,提供了實現List介面的基本實現
  //Deque介面, A linear collection that supports element insertion and removal at both ends.  
  //The name <i>deque</i> is short for "double ended queue" and is usually pronounced "deck"

public interface Deque<E> extends Queue<E>

//所以這裡就可以知道為什麼LinkedList可以模擬佇列,雙端佇列,以及Stack棧了

2.重要屬性

transient int size = 0;//記錄List大小
//接下來分別是兩個Node引用,分別指向連結串列頭和連結串列尾
transient Node<E> first;
transient Node<E> last;

//接下就是連結串列中節點的定義,可以看到JDK1.8把節點都統一為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;
        }
    }
//及其簡單的定義,雙向連結串列,向前連結,向後向後連結,元素

3.構造器

//(1)無參構造器
  public LinkedList() {
    }
  //(2)帶有集合的構造器
  public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }
//呼叫addAll將現有集合內所有元素放到LinkedList中
  public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }
  //將整個集合c中的元素加入連結串列中   
  public boolean addAll(int index, Collection<? extends E> c) {
        checkPositionIndex(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        if (numNew == 0)
            return false;

        Node<E> pred, succ;
        //插入到結尾
        if (index == size) {
            succ = null;
            pred = last;
        } else {//插入到中間
    //這裡succ則為原來在index位置的節點
            succ = node(index);
            pred = succ.prev;
        }

        for (Object o : a) {
            @SuppressWarnings("unchecked") E e = (E) o;
            //建立新的Node節點,其中newNode的前向節點為pred,後向節點沒有定義
            Node<E> newNode = new Node<>(pred, e, null);
            //pred==null,則此節點為首節點
            if (pred == null)
                first = newNode;
            else
                //當節點不是首節點時,定義前向節點的後向節點為當前節點
                pred.next = newNode;
            pred = newNode;
        }

        if (succ == null) {
            last = pred;
        } else {
            //將原來的連結串列加入
            pred.next = succ;
            succ.prev = pred;
        }

        size += numNew;
        modCount++;
        return true;
    }

4.常用方法原始碼分析

(1). add(E e)

//預設add方法,將節點放入連結串列尾部,同offer方法
  public boolean add(E e) {
        linkLast(e);
        return true;
    }

    //將節點放入連結串列尾部
    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++;
    }
//將元素連結放到指定位置
public void add(int index, E element) {
          //該方法主要是檢視index是否合法,在範圍內,否則丟擲異常
        checkPositionIndex(index);
        //當index是末尾時,直接連結到結尾
        if (index == size)
            linkLast(element);
        else
           //否則找到index位置的原來節點,插入到其前面
            linkBefore(element, node(index));
    }

   //取出index位置的node節點
    Node<E> node(int index) {
        // assert isElementIndex(index);
        //這裡有一處非常值得注意
        //size>>1表示的是向右移位1,該方法其實相當於除以2,去得一半的值
        //當index<size/2時,表明index在前半部分,則正序找
        //否則在後半部分,則倒序查詢,節省了時間
        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;
        }
    }

//linkBefore 方法
    //這個方法是將節點插入到succ節點的前面,
//由於是在指定位置插入節點,所以要將原來的節點連結到新節點後面
    void linkBefore(E e, Node<E> succ) {
        // assert succ != null;
        final Node<E> pred = succ.prev;
        final Node<E> newNode = new Node<>(pred, e, succ);
        succ.prev = newNode;
        if (pred == null)
            first = newNode;
        else
            //這裡一定要注意,雙向連結串列,一定要將pred節點的next節點定義為當前節點
            pred.next = newNode;
        size++;
        modCount++;
    }

  (2).addLast(),addFirst()方法

addLast()等同於add()方法,addFirst是在連結串列頭插入節點

//將新節點放入到連結串列尾部
 public void addLast(E e) {
        linkLast(e);
    }

//在連結串列頭插入節點
   public void addFirst(E e) {
        linkFirst(e);
    }

    //將新節點設定為首節點
  private void linkFirst(E e) {
        final Node<E> f = first;
        final Node<E> newNode = new Node<>(null, e, f);
        first = newNode;
        if (f == null)
            last = newNode;
        else
            f.prev = newNode;
        size++;
        modCount++;
    }

(3). getFirst(),getLast()獲取頭節點和尾節點

/**
     * Returns the first element in this list.
     *
     * @return the first element in this list
     * @throws NoSuchElementException if this list is empty為空會丟擲異常
     */
    public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }

    /**
     * Returns the last element in this list.
     *
     * @return the last element in this list
     * @throws NoSuchElementException if this list is empty
     */
    public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }

     (4). removeFirst(),removeLast()方法

/**
     * 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() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }

//unlinkFirst()即解開並返回頭節點
   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;

        if (next == null)
            last = null;//此時連結串列為空
        else
            next.prev = null;
        size--;
        modCount++;
        return element;
    }
/**
     * Removes and returns the last element from this list.
     *
     * @return the last element from this list
     * @throws NoSuchElementException if this list is empty
     */
    public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }

    /**
     * Unlinks non-null last node l.
     */
    private E unlinkLast(Node<E> l) {
        // assert l == last && l != null;
        final E element = l.item;
        final Node<E> prev = l.prev;
        l.item = null;
        l.prev = null; // help GC
        last = prev;
        if (prev == null)
            first = null;
        else
            prev.next = null;
        size--;
        modCount++;
        return element;
    }

(5). contains(Object o)
    檢視連結串列中是否存有某個元素

public boolean contains(Object o) {
        return indexOf(o) != -1;
    }
    //indexOf()這個方法返回物件O在連結串列中的位置
   public int indexOf(Object o) {
        int index = 0;
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null)
                    return index;
                index++;
            }
        } else {
            //同樣呼叫的也是equals方法判斷兩個值是否相等
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item))
                    return index;
                index++;
            }
        }
        return -1;//沒有找到時返回-1
    }

(6). get(int index)

獲取指定index位置的元素

/**
     * Returns the element at the specified position in this list.
     *
     * @param index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }

  (7).set(int index,E element)

set修改指定位置的元素

//主要還是定位獲取節點之後再修改
   public E set(int index, E element) {
        checkElementIndex(index);
        Node<E> x = node(index);
        E oldVal = x.item;
        x.item = element;
        return oldVal;
    }

(8).搜尋元素所在位置indexOf(Object o),lastIndexOf(Object o)

分為正向indexOf(),即第1次插入時匹配的元素位置和反向lastIndexOf(),即最後一次插入匹配的位置

//indexOf()這個方法返回物件O在連結串列中的位置
    public int indexOf(Object o) {
        int index = 0;
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null)
                    return index;
                index++;
            }
        } else {
            //同樣呼叫的也是equals方法判斷兩個值是否相等
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item))
                    return index;
                index++;
            }
        }
        return -1;
    }

    //反向查詢
    //有index的時候,必然會有lastIndexOf
    public int lastIndexOf(Object o) {
        int index = size;
        if (o == null) {
            for (Node<E> x = last; x != null; x = x.prev) {
                index--;
                if (x.item == null)
                    return index;
            }
        } else {
            for (Node<E> x = last; x != null; x = x.prev) {
                //這裡值得注意的是,index先--,因為你是從size位置開始的,所以要先--
                index--;
                if (o.equals(x.item))
                    return index;
            }
        }
        return -1;
    }

5.模擬Queue操作原始碼分析

再次強調一次這裡queue先進先出,在隊尾入隊,隊首出隊

(1).首先是檢索隊首,但不出隊的操作,peek(),element()

/**
     * Retrieves, but does not remove, the head (first element) of this list.
     *
     * @return the head of this list, or {@code null} if this list is empty
     * @since 1.5
     */最常用操作,peek(),若為空會,返回null
    public E peek() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }

    /**
     * Retrieves, but does not remove, the head (first element) of this list.
     *
     * @return the head of this list
     * @throws NoSuchElementException if this list is empty
     * @since 1.5
     *///若為空會丟擲異常
    public E element() {
        return getFirst();
    }

//再回頭看一眼getFirst(),
   public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();//丟擲異常
        return f.item;
    }

(2).出隊操作,取出隊首元素,poll(),remove()

/**
     * Retrieves and removes the head (first element) of this list.
     *
     * @return the head of this list, or {@code null} if this list is empty
     * @since 1.5
     */
    public E poll() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

    /**
     * Retrieves and removes the head (first element) of this list.
     *
     * @return the head of this list
     * @throws NoSuchElementException if this list is empty
     * @since 1.5
     */
    public E remove() {
        return removeFirst();
    }

    public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }

(3).隊尾插入元素offer()

/**
     * Adds the specified element as the tail (last element) of this list.
     *
     * @param e the element to add
     * @return {@code true} (as specified by {@link Queue#offer})
     * @since 1.5
     */
    public boolean offer(E e) {
        return add(e);
    }

6. 模擬雙端佇列Deque操作原始碼分析

雙端佇列,其實就是整條連結串列頭尾都操作,有了前面的基礎,這裡應該非常簡單了

(1).在隊首,隊尾插入元素,offerFirst(),offerLast()

其實就是分別呼叫addFirst(E e)和addLast(E e)方法

/**
     * Inserts the specified element at the front of this list.
     *
     * @param e the element to insert
     * @return {@code true} (as specified by {@link Deque#offerFirst})
     * @since 1.6
     */
    public boolean offerFirst(E e) {
        addFirst(e);
        return true;
    }

    /**
     * Inserts the specified element at the end of this list.
     *
     * @param e the element to insert
     * @return {@code true} (as specified by {@link Deque#offerLast})
     * @since 1.6
     */
    public boolean offerLast(E e) {
        addLast(e);
        return true;
    }

(2).檢索隊首,隊尾元素,但不出隊peekFirst(),peekLast()

/**
     * Retrieves, but does not remove, the first element of this list,
     * or returns {@code null} if this list is empty.
     *
     * @return the first element of this list, or {@code null}
     *         if this list is empty
     * @since 1.6
     */
    public E peekFirst() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
     }

    /**
     * Retrieves, but does not remove, the last element of this list,
     * or returns {@code null} if this list is empty.
     *
     * @return the last element of this list, or {@code null}
     *         if this list is empty
     * @since 1.6
     */
    public E peekLast() {
        final Node<E> l = last;
        return (l == null) ? null : l.item;
    }

(3). 出隊操作,取出隊首,隊尾