Java List集合源碼分析(JDK 1.8)

java的集合是常用的類,也是面試官非常喜歡的問題。集合可以分為set集合、list集合和map集合list集合,這篇博客會分析list集合。時間非常緊迫的同學可以直接看最后的總結。

首先看一下List類的體系結構,JDK版本為1.8.0

List體系

List體系中有三個我們常用的類:ArrayList、Vector、LinkedList。
下面主意分析這三個類

ArrayList

ArrayList內部使用數組來保存對象,在數組長度不夠的時候,增加數組的長度。

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable

ArrayList繼承了AbstractList,實現了List、Random、Colleable、Serializable接口,ArrayList有一個泛型,用來指定保存的對象類型。

ArrayList的成員變量

    private static final long serialVersionUID = 8683452581122892189L;

    /**
     * 默認的數組容量
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * 默認空數組
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * 默認空數組
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * 用于保存數據的數組
     * 不可序列化
     */
    transient Object[] elementData; // 

    /**
     * 當前保存的數據數量
     *
     * @serial
     */
    private int size;

ArrayList的構造方法

    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

無參構造方法中將elementData默認初始化為DEFAULTCAPACITY_EMPTY_ELEMENTDATA,也就是一個空的數組。

    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];   //如果指定的初始容量initialCapacity大于0,就創(chuàng)建initialCapacity大小的數組
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;    //如果initialCapacity等于0,將elementData 初始化為空數組
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
        }
    }

一個參數int initialCapacity的構造方法中,根據傳入的初始化容量,創(chuàng)建不同長度的數組。如果initialCapacity大于0,創(chuàng)建initialCapacity長度的數組;如果initialCapacity等于0,使elementData 指向一個長度為0的數組;如果initialCapacity長度小于0,拋出異常。

    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();                     //將傳入的集合賦值給elementData
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

一個參數Collection<? extends E> c的構造方法,將傳入的集合賦值給elementData,更新數組長度size。
?值得是泛型通配符,可以指代不同的泛型,具體可以看這一篇文章Java總結篇系列:Java泛型

private void grow(int minCapacity)

grow方法是進行l(wèi)ist中數組擴容的,傳入當前需要的最小數組長度。下面看源碼。

    private void grow(int minCapacity) {
        int oldCapacity = elementData.length;                          //獲得數組現有的長度
        int newCapacity = oldCapacity + (oldCapacity >> 1);   //數組新長度是現有長度的1.5倍
        if (newCapacity - minCapacity < 0)                               //如果新長度仍然不滿足需求的長度
            newCapacity = minCapacity;                                    //就設置新長度為需求的長度
        if (newCapacity - MAX_ARRAY_SIZE > 0)                  //如果長度超過所能承受的最大長度Integer.MAX_VALUE - 8
            newCapacity = hugeCapacity(minCapacity);            //使用hugeCapacity方法設置新長度
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);  //復制數組元素
    }

上面程序中首先獲得數組的現有長度,然后設置數組新長度是現有長度的1.5倍,如果新長度仍小于所需長度,則設置新長度等于所需長度。如果新長度大于最大長度,則使用hugeCapacity方法設置新長度。下面看hugeCapacity方法。

    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow              //如果長度超過整形的最大值,則拋出異常
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?    //返回整形的最大長度
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

所以,ArrayList的最大長度是整型的最大值,超過這個值就會報OutOfMemoryError()。

public boolean add(E e)

    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // 數據長度自增
        elementData[size++] = e;
        return true;
    }

在add方法中,首先會使用ensureCapacityInternal(size + 1)方法進行數據數組擴容,然后將待插入的元素插入到數組末尾。

    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {   //如果當前數據數組是空數組
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);  //最小長度是10和所需長度的最大值
        }

        ensureExplicitCapacity(minCapacity);                              //數據數組擴容
    }
    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;                                                                    //操作數自增
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);                                                      //數據數組擴容
    }

add方法總結:
add方法中,首先會對數據數組進行擴容(如果現有的容量小于所需的容量,就擴容)。如果第一次添加數據,也就是數據數組是空數組的時候,設置最小的所需長度是10(我認為是為了避免數據數組在剛開始的時候長度增長地過慢,導致經常擴容,影響效率),然后使用grow方法對數據進行擴容(每次增長為原來的1.5倍)。

public boolean addAll(Collection<? extends E> c)

    public boolean addAll(Collection<? extends E> c) {
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityInternal(size + numNew);  // Increments modCount
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
        return numNew != 0;
    }

首先將輸入的待插入集合轉化為數組,然后對數據數組擴容,復制數組,更新size,返回。

public E set(int index, E element)

    public E set(int index, E element) {
        rangeCheck(index);                //檢查數組是否越界

        E oldValue = elementData(index);
        elementData[index] = element;         //設置新數據
        return oldValue;                          //返回舊數據
    }

set方法中邏輯比較簡單,首先判斷數組是否越界,如果越界拋出IndexOutOfBoundsException異常,然后將新數據設置到指定位置,返回舊數據。

public E remove(int index)

    public E remove(int index) {
        rangeCheck(index);             //檢查數組是否越界

        modCount++;
        E oldValue = elementData(index);     //取得需要刪除的元素

        int numMoved = size - index - 1;           //獲得需要移動的數據長度
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,   //移動數據,填補空缺
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work       //最后一個數據設置為null

        return oldValue;
    }

remove方法的邏輯同樣簡單,首先檢查index是否越界(如果越界,拋出IndexOutOfBoundsException),然后獲得需要刪除的元素,刪除中間的一個元素后,后面的元素都需要前移一位,原來最后位置的元素設置為null,最后返回移除的元素。

public E get(int index)

    public E get(int index) {
        rangeCheck(index);

        return elementData(index);
    }

get方法邏輯比較簡單,首先檢查index是否越界,然后然后返回指定位置的數據

內部類private class Itr implements Iterator<E>

ArrayList中有個內部類Itr,實現了Iterator接口,也就是我們常說的迭代器。

   private class Itr implements Iterator<E> {
        int cursor;       // 游標,指向下一個可以返回的數據
        int lastRet = -1; // 游標,指向最后一個已返回的元素
        int expectedModCount = modCount;   //操作次數

        public boolean hasNext() {               //通過比較ArrayList中的成員變量size和迭代器的游標cursor,判斷否是還有下一個元素
            return cursor != size;
        }

        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();                   //如果迭代器中的操作數和ArrayList中的操作數不相等,就拋出異常。因此,我們在使用迭代器的時候,不應該使用ArrayList自身的add,remove,set等方法,否則迭代器會拋出異常!
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];                    //返回數據,游標后移,設置lastRet為剛剛返回的元素
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);         //移除上一個返回的元素
                cursor = lastRet;
                lastRet = -1;                                  //重新設置lastRet為-1,所以next一次,只能remove一次。
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> consumer) {
            Objects.requireNonNull(consumer);
            final int size = ArrayList.this.size;
            int i = cursor;
            if (i >= size) {
                return;
            }
            final Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            while (i != size && modCount == expectedModCount) {
                consumer.accept((E) elementData[i++]);
            }
            // update once at end of iteration to reduce heap write traffic
            cursor = i;
            lastRet = i - 1;
            checkForComodification();
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

迭代器總結:

1.迭代器封裝了對集合元素的next和remove操作,不需要了解集合底層具體的實現,只需要使用迭代器進行統(tǒng)一處理
2.迭代器的remove操作是調用ArrayList的remove操作,迭代器本身不對ArrayList的結構產生變化。
2.迭代器內部會保存一個操作數,每次操作,迭代器都會檢查自身的操作數和ArrayList的操作數是否相等,如果不相等會拋出異常。因此,我們在使用迭代器的時候再獲取迭代器的對象,并且在使用迭代器的過程中,不應該使用ArrayList本身對數進行結構性的改變(add,remove等)。

Vector

public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable

Vector和ArrayList的實現原理大致相同,都是在內部使用數組來保存數據,add和remove也都是先擴容,然后對數組進行操作。最大的不一樣是Vector內部方法都用Synchronized修飾,也就是多線程同步的。并且數組擴容的方法也不太一樣。
首先看構造方法

    public Vector(int initialCapacity, int capacityIncrement) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
        this.capacityIncrement = capacityIncrement;
    }

    /**
     * 
     */
    public Vector(int initialCapacity) {
        this(initialCapacity, 0);
    }

    /**
     * 
     */
    public Vector() {
        this(10);
    }

Vector有三個構造方法,分別是無參,一個參數(初始化容量),兩個參數(初始化容量,每次擴容增長的容量)。前兩個構造方法最后都是調用兩個參數的構造方法。
可以看到,如果不設置默認的初始容量是10,默認每次擴容增加的容量是0。

private void grow(int minCapacity)

    private void grow(int minCapacity) {
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?    //如果默認的擴容增量等于0,就設置新的容量為舊容量的兩倍,否則根據容量增量增加容量。
                                         capacityIncrement : oldCapacity);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

grow方法中,會判斷現在的擴容增量值是不是等于0,如果等于0,則新容量是舊容量的兩倍,否則,根據擴容增量設置新的容量。

Vector總結:

1.基本原理和ArrayList相同,內部使用數組保存數據,在需要的時候擴容數組
2.構造方法方法中,可以設置初始的容量和每次擴容增加的容量。默認初始容量是10,每次擴容增加的容量是0。
3.對數據的結構性操作的函數都使用Synchronized來修飾(如add,remove,setSize),是線程安全的,但是多線程環(huán)境下效率比較低。
4.每次擴容,如果現有設置的擴容增量為0,則新容量為舊容量的兩倍,否則,新容量為舊容量+擴容增量。

LinkedList

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable

ArrayList和Vector內部都是用數組來存儲元素,LinkedList內部使用雙向鏈表來存儲數據(jdk1.8.0中不是循環(huán)鏈表)。下面的分析只對源碼中的思路進行分析,不對具體的鏈表操作進行分析。

成員變量

    transient int size = 0;   //已存儲元素的多少

    /**
     * 指向鏈表中第一個元素的指針
     */
    transient Node<E> first;

    /**
     * 指向鏈表中最后一個元素的指針
     */
    transient Node<E> last;

LinkedList中保存了指向第一個元素和最后一個元素的指針。

構造方法

    public LinkedList() {
    }

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

提供了兩個構造方法,一個沒有任何邏輯,一個傳入數據集合,調用addAll插入數據集合。

boolean addAll(int index, Collection<? extends E> 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);      //使用node(index)查找到指定位置的元素
            pred = succ.prev;
        }

        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指針
            last = pred;
        } else {
            pred.next = succ;
            succ.prev = pred;
        }

        size += numNew;      //修改size
        modCount++;           //修改操作數
        return true;
    }
    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;
        }
    }

在AddAll方法中首先使用node(int index)找到插入點,然后將數據插入到雙向鏈表中

public boolean add(E e)

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

調用linkLast將元素插入到鏈表尾部,具體怎么插入就不分析了,就是雙向鏈表的插入操作。

public boolean remove(Object o)

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

在remove(Object o)方法中,首先判斷o是不是null,如果是,則通過for循環(huán)查到鏈表中第一個值為null的結點;否則,通過for循環(huán)找到指定結點,刪除。

public E get(int index)

    public E get(int index) {
        checkElementIndex(index);      //檢查是否越界
        return node(index).item;           //使用node獲取指定位置的結點
    }

public E peek()

    public E peek() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }

返回鏈表中的第一個元素

public E poll()

    public E poll() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

首先獲取鏈表中第一個元素,斷開其連接,返回該元素。

public boolean offer(E e)

    public boolean offer(E e) {
        return add(e);
    }

offer方法中調用add方法將元素插入到鏈表末尾,

public void push(E e)

    public void push(E e) {
        addFirst(e);
    }

使用addFirst(e)將數據插入到鏈表開頭

public E pop()

    public E pop() {
        return removeFirst();
    }

使用removeFirst返回鏈表的頭結點,斷開頭結點與其他結點的連接

public void clear()

    public void clear() {
        for (Node<E> x = first; x != null; ) {   //將結點的引用指向null,使實例對象可以被GC
            Node<E> next = x.next;
            x.item = null;
            x.next = null;
            x.prev = null;
            x = next;
        }
        first = last = null;                 //重置頭節(jié)點和尾結點
        size = 0;                             //設置size為0
        modCount++;
    }

LinkedList總結

1.使用雙向鏈表來保存數據,數據插入,刪除都是通過對鏈表操作來實現的。
2.繼承了queue接口,可以當作隊列來使用。也提供了棧的方法,也可以當作棧使用。

List集合的總結

image.png
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容