LinkedList其實就那么一回事兒之源碼分析


上篇文章《ArrayList其實就那么一回兒事兒之源碼分析》,給大家談了ArrayList, 那么本次,就給大家一起看看同為List 家族的LinkedList。 下面就直接看源碼吧:

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
    transient int size = 0;
    
    //Node 是LinkedList的一個內部類,下面貼出了這個內部類的源碼, 
    //主要用於保存上一個、當前和下一個元素的引用
    
    //頭(第一個)元素
    transient Node<E> first;

    //尾(最后一個)元素
    transient Node<E> last;

    public LinkedList() {
    }

    //構造方法傳入Collection, 那么將Collection轉換為鏈表結構
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }
    
    public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }
    
    
    /**
     * 內部類
     */
    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 addAll(int index, Collection<? extends E> c) {
        //index >= 0 && index <= size
        checkPositionIndex(index);

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

        //succ保存的是index位置的元素
        Node<E> pred, succ;
        if (index == size) {
            //當index == size 的時候, 當前元素的上一個元素就是之前已存在鏈表的最后一個元素
            //(如果覺得有點繞, 可以再好好體會一下)
            succ = null;
            pred = last;
        } else {
            //當index != size 的時候, 那么index就一定出現在之前鏈表中
            //此處的調用的node方法,下面源碼也已經給出,
            //node方法的主要作用就是判斷index所處位置是在之前鏈表的上半部分還是下半部分,
            //在上半部分就從第一個元素開始循環,循環到index位置時返回元素, 如果是在后半部分,那么就從最后一個元素往前循環,循環到index位置時返回元素
            succ = node(index);
            //得到index所在元素的上一個元素引用
            pred = succ.prev;
        }
        
        //別急,上面還在熱身, 這兒才開始轉換
        
        for (Object o : a) {
            @SuppressWarnings("unchecked") E e = (E) o;
            //構造Node對象, 此時Node對象持有對前一個元素以及當前元素的引用
            Node<E> newNode = new Node<>(pred, e, null);
            if (pred == null)
                //如果前一個元素為null, 那么說明之前不存在鏈表,此元素將設置為鏈表的第一個元素
                first = newNode;
            else
                //如果已存在鏈表,那么就從之前鏈表的index位置開始插入
                pred.next = newNode;
            pred = newNode;
        }

        if (succ == null) {
            last = pred;
        } else {
            pred.next = succ;
            succ.prev = pred;
        }

        size += numNew;
        modCount++;
        return true;
    }
    
    private void checkPositionIndex(int index) {
        if (!isPositionIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    
    private boolean isPositionIndex(int index) {
        return index >= 0 && index <= size;
    }
    
    //上面已經把這方法解釋了一遍,這兒就不多說了,貼出來就為了讓大家看得直觀
    Node<E> node(int index) {
        // assert isElementIndex(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;
        }
    }
    
    
    
    //下面開始分析常用的add 、 remove 方法
    
    //先看看add方法
    public void add(int index, E element) {
        checkPositionIndex(index);
        
        //相信通過上面的分析,你已經能夠猜到add 改怎么做了,
        //當index == size的時候, 已存在鏈表的最后一個元素就是當前待插入元素的上一個節點(元素)
        //當index != size的時候, 老規矩,先找出index位置的節點元素, 然后再插入(上面已經詳解,這兒只做概述,加深印象)
        if (index == size)
            linkLast(element);
        else
            linkBefore(element, node(index));
    }
    
    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++;
    }
    
    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 = newNode;
        size++;
        modCount++;
    }
    
    
    //接下來再看看remove方法
    public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }
    
    //此方法作用: 先得到index位置的node, 然后拿到其上一個元素(pre)和下一個元素(next),
    //將上一個元素(pre)的下一個元素設置為index的next, 此時,就成功的刪除了index位置的元素,
    //舉個例子吧: 李四左手牽着張三,右手牽着王五, 現在我們要刪除李四, 那么只需要直接將張三的手牽向王五, 明白了吧
    E unlink(Node<E> x) {
        // assert x != null;
        final E element = x.item;
        final Node<E> next = x.next;
        final Node<E> prev = x.prev;

        if (prev == null) {
            first = next;
        } else {
            prev.next = next;
            x.prev = null;
        }

        if (next == null) {
            last = prev;
        } else {
            next.prev = prev;
            x.next = null;
        }

        x.item = null;
        size--;
        modCount++;
        return element;
    }
    
    
    
}

通過代碼分析,我們可以看到,LinkedList其實是基於雙向鏈表實現的, 因此,書上所講的LinkedList的特性咱也別去記了, 知道鏈表的特性就對了, 到此,不得不談談LinkedList和ArrayList的區別:

ArrayList基於數組實現,因此具有: 有序、元素可重復、插入慢、 索引快 這些數組的特性; 

LinkedList 基於雙向鏈表實現, 因此具有鏈表 插入快、 索引慢的特性;

了解了它們的特性之后,你就可以根據實際需要,選擇合適的List了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM