1. 程式人生 > >19java原始碼解析-LinkedList(一)

19java原始碼解析-LinkedList(一)

其他 原始碼解析 https://blog.csdn.net/qq_32726809/article/category/8035214

通過大體瀏覽原始碼,可知,Linkedlist的儲存機構是一個連結串列

類的宣告

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
  • AbstractSequentialList
  • 順序集合介面的最小實現
  • 若是隨機插入,則優先用AbstractList
  • Deque
  • 刪除和插入的集合,雙端對列

節點內部類

  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;
        }
    }

next 指的是下一個節點,prev指的是上一個節點,item指的是當前節點的元素。可以將next和perv理解為指標。

屬性

 

transient int size = 0;
transient Node<E> first;/*第一個節點*/
transient Node<E> last;/*最後一個節點*/

建構函式

 public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }

按照集合的迭代器的元素獲取建構函式

3方法

3.1linkFirst

把元素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++;
    }

將node節點上一個元素置為null,下一個元素為 原第一個元素,並將現在的元素賦予 first

3.2linkLast

把元素e多為最後一個元素

 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++;
    }

將當前元素新建一個node節點,把尾部的節點作為這個節點的上一個節點,把下一個節點置為null,把這個節點作為上一個節點的下一個節點,總的來說,就是把新節點與原來的節點連線起來.

3.3linkBefore

把元素e插入到 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 = newNode;
        size++;
        modCount++;
    }

類似於在兩個火車車廂中間插入新的車廂,需要舊的車廂與新的車廂頭尾相連,並改變車廂數

3.4unlinkFirst

將第一個元素移除連結

 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;
    }

3.5unlinkLast

將最後一個元素移除處連結

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;
    }

3.6getFirst

獲取第一個元素

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

3.7getLast

獲取最後一個元素

 public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }

3.8removeFirst(),removeLast(),addFirst(E e),addLast(E e)

這些方法用的是上面已經講過的方法

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

    /**
     * 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);
    }

    /**
     * Inserts the specified element at the beginning of this list.
     *
     * @param e the element to add
     */
    public void addFirst(E e) {
        linkFirst(e);
    }

    /**
     * Appends the specified element to the end of this list.
     *
     * <p>This method is equivalent to {@link #add}.
     *
     * @param e the element to add
     */
    public void addLast(E e) {
        linkLast(e);
    }

3.9contains

判斷元素是否在集合中,其實就是判斷節點的索引是否大於小於0

 public boolean contains(Object o) {
        return indexOf(o) != -1;
    }
    
 public int indexOf(Object o) {/*--------------1*/
        int index = 0;
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null)
                    return index;
                index++;
            }
        } else {
            for (Node<E> x = first; x != null; x = x.next) {/*--------------2*/
                if (o.equals(x.item))
                    return index;
                index++;
            }
        }
        return -1;
    }
  • 1處方法的是獲取元素的所在位置
  • 2處是遍歷鏈條,對每個節點進行判斷。

3.10add

 public boolean add(E e) {
        linkLast(e);
        return true;
    }

新新增的元素會被新增到最後

3.11 remove

通過遍歷連結串列移除元素

 public boolean remove(Object o) {
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null) {
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }
    
 E unlink(Node<E> x) {  /*-------------1*/
        // 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;
    }

1處的函式是刪除元素,然後將刪除後的兩端重新連結起來

3.12addAll

  public boolean addAll(Collection<? extends E> c) {
        return addAll(size, 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 = node(index);
            pred = succ.prev;
        }


        /*-----------------------1*/
        for (Object o : a) {
            @SuppressWarnings("unchecked") E e = (E) o;
            Node<E> newNode = new Node<>(pred, e, 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;
    }
   

1處為核心程式碼,就是把集合轉化的陣列進行遍歷,然後將元素新建成節點,再將節點連結起來

3.13clear

將所有連線元素設定為空

  public void clear() {
        // Clearing all of the links between nodes is "unnecessary", but:
        // - helps a generational GC if the discarded nodes inhabit
        //   more than one generation
        // - is sure to free memory even if there is a reachable Iterator
        for (Node<E> x = first; x != null; ) {
            Node<E> next = x.next;
            x.item = null;
            x.next = null;
            x.prev = null;
            x = next;
        }
        first = last = null;
        size = 0;
        modCount++;
    }