ArrayList用法及源碼解析

轉載請註明出處:http://blog.csdn.net/github_39430101/article/details/76166174

ArrayList簡介

ArrayList實現了List接口,內部以數組存儲數據,允許重複的值。由於內部是數組實現,所以ArrayList具有數組所有的特性,通過索引支持隨機訪問,查詢速度快,但是插入和刪除的效率比較低。ArrayList是非線程安全的,所以建議在單線程中使用ArrayList,在多線程中選擇Vector或者CopyOnWriteArrayList。

ArrayList結構

這裏寫圖片描述

和LinkedList主要區別

1.ArrayList是實現了基於動態數組的數據結構,LinkedList基於鏈表的數據結構。
2.對於隨機訪問get和set,ArrayList優於LinkedList,因爲LinkedList要移動指針。
3.對於新增和刪除操作add和remove,LinedList比較佔優勢,因爲ArrayList要移動數據。

常用方法

返回類型 方法 用法
boolean add(E e) 將指定的元素添加到此列表的尾部
void add(int index, E element) 將指定的元素插入此列表中的指定位置
void clear() 移除此列表中的所有元素
Object clone() 返回此 ArrayList 實例的淺表副本
boolean contains(Object o) 如果此列表中包含指定的元素,則返回 true
E get(int index) 返回此列表中指定位置上的元素
int indexOf(Object o) 返回此列表中首次出現的指定元素的索引,或如果此列表不包含元素,則返回 -1
int lastIndexOf(Object o) 返回此列表中最後一次出現的指定元素的索引,或如果此列表不包含索引,則返回 -1
boolean isEmpty() 如果此列表中沒有元素,則返回 true
E remove(int index) 移除此列表中指定位置上的元素
boolean remove(Object o) 刪除ArrayList中指定的元素
protected void removeRange(int fromIndex, int toIndex) 移除列表中索引在 fromIndex(包括)和 toIndex(不包括)之間的所有元素
E set(int index, E element) 用指定的元素替代此列表中指定位置上的元素
int size() 返回此列表中的元素數
Object[] toArray() 按適當順序(從第一個到最後一個元素)返回包含此列表中所有元素的數組
void trimToSize() 將此 ArrayList 實例的容量調整爲列表的當前大小

Demo

package com.code.array;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ArrayTest {

    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        // add方法
        list.add("張三");
        list.add("李四");
        list.add("王麻子");
        list.add("趙雲");
        list.add("關羽");
        list.add("曹操");

//      第一種遍歷方法
        for(int i=0;i<list.size();i++){
            System.out.println(list.get(i));   
        }
//      第二種遍歷方法 foreach循環
        for(String v :list) {
            System.out.println(v);
        }

//      第三種遍歷方法
        Iterator<String> i = list.iterator();
        while(i.hasNext()) {
            System.out.println(i.next());
        } 

        list.add(0, "張飛");


        if(list.contains("趙雲")) {
            System.out.println("我乃常山趙子龍");
        } else System.out.println("沒有趙雲");


        System.out.println(list.indexOf("趙雲"));
        //lastIndexOf(Object o)

        System.out.println(list.lastIndexOf("張三"));

        System.out.println(list.isEmpty());
        //循環刪除
        for (int x =list.size()-1;x>=0;x--) {
            list.remove(list.get(x));
        }
    }
}

ArrayList源碼


package java.util;

import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
    //序列版本號
    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 = {};
    //保存ArrayList數組數據
    transient Object[] elementData; 
    //數組包含元素的個數
    private int size;

    /********** 三個構造函數 *********/

    //帶參構造函數
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    //無參構造函數
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
    //參數爲Collection的構造方法
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        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;
        }
    }
    /*************** ArrayList擴容原理 ************/
    //修改當前容量爲實際個數
    public void trimToSize() {
        modCount++;
        //如果當前個數小於數組的容量,則把數組大小設置爲當前的size
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }

    //將此 ArrayList 實例的容量調整爲列表的當前大小,是提供給外界的方法,真正的擴容是在下面的private方法裏
    public void ensureCapacity(int minCapacity) {
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
            ? 0
            : DEFAULT_CAPACITY;

        if (minCapacity > minExpand) {
            ensureExplicitCapacity(minCapacity);
        }
    }

    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }
   ensureExplicitCapacity(minCapacity);
    }

    //ArrayList擴容
    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;
        //如果新的數組大小大於之前數組大小,則調用擴容方法
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
    //分配的最大數組空間
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    //擴容
    private void grow(int minCapacity) {
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);//新的容量=原來的容量+原來的容量/2
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
    //
    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }
    /********* 常用方法 **************/
    //返回當前數組大小
    public int size() {
        return size;
    }
    //判斷數組是否爲空
    public boolean isEmpty() {
        return size == 0;
    }
    //判斷數組是否包含某個元素
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }
    //返回此列表中首次出現的指定元素的索引
    public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }
    //返回此列表中最後一次出現的指定元素的索引
    public int lastIndexOf(Object o) {
        if (o == null) {
            for (int i = size-1; i >= 0; i--)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = size-1; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

    //克隆
    public Object clone() {
        try {
            ArrayList<?> v = (ArrayList<?>) super.clone();
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }

    //返回一個Object數組,包含ArrayList中所有的元素
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    //返回ArrayList的模板數組
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }

    // Positional Access Operations

    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

    //返回此列表中指定位置上的元素
    public E get(int index) {
        rangeCheck(index);
        return elementData(index);
    }

    //用指定的元素替代此列表中指定位置上的元素
    public E set(int index, E element) {
        rangeCheck(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }
    //將指定的元素添加到此列表的尾部
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    // 將指定的元素插入此列表中的指定位置
    public void add(int index, E element) {
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }

     //移除此列表中指定位置上的元素
    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

        return oldValue;
    }

    //刪除ArrayList中指定的元素
    public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }

       //快速刪除,跳過邊界檢查且沒有返回值
    private void fastRemove(int index) {
        modCount++;
        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
    }

      //移除此列表中所有元素
    public void clear() {
        modCount++;

        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
    }

    //將集合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;

    //從指定的位置開始,將指定 collection 中的所有元素插入到此列表中
    public boolean addAll(int index, Collection<? extends E> c) {
        rangeCheckForAdd(index);
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityInternal(size + numNew);  // Increments modCount
        int numMoved = size - index;
        if (numMoved > 0)
        System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);
        System.arraycopy(a, 0, elementData, index, numNew);
        size += numNew;
        return numNew != 0;
    }

    //除從fromIndex到toIndex之間的數據,不包括toIndex位置的數據
    protected void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);

        // clear to let GC do its work
        int newSize = size - (toIndex-fromIndex);
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        size = newSize;
    }

    //範圍檢查
    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

      //由add和addAll使用的rangeCheck的一個版本
    private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }

    //刪除ArrayList中所有集合C中包含的數據
    public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }

    //刪除ArrayList中除了集合C中包含的數據外的其他所有數據
    public boolean retainAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, true);
    }
    //批量刪除
    private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false;
        try {
            for (; r < size; r++)
                if (c.contains(elementData[r]) == complement)
                    elementData[w++] = elementData[r];
        } finally {
      //保留與AbstractCollection的行爲兼容性
            if (r != size) {
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);
                w += size - r;
            }
            if (w != size) {
                // clear to let GC do its work
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;
                size = w;
                modified = true;
            }
        }
        return modified;
    }
/************ ArrayList與IO *********/

//將ArrayList的容量和元素都寫入到輸出流中
private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
        int expectedModCount = modCount;
        s.defaultWriteObject();
        s.writeInt(size);
        for (int i=0; i<size; i++) {
            s.writeObject(elementData[i]);
        }

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

    //先將ArrayList的“容量”讀出,然後將“所有的元素值”讀出 
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        elementData = EMPTY_ELEMENTDATA;
        s.defaultReadObject();

        s.readInt(); 

        if (size > 0) {
            ensureCapacityInternal(size);

            Object[] a = elementData;

            for (int i=0; i<size; i++) {
                a[i] = s.readObject();
            }
        }
    }

注意: ArrayList循環遍歷並刪除元素的常見錯誤

錯誤一、

public static void main(String[] args){
    List<String> list = new ArrayList<String>();
    list.add("劉備");
    list.add("關羽");
    list.add("張飛");
    for (String s:list){
        list.remove(s);
    }
}

這裏寫圖片描述
錯誤原因:foreach寫法是對迭代器的簡寫,我們的remove方法修改了modCount的值

   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

        return oldValue;
    }

父類AbstractList checkForComodification方法

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

這裏會做迭代器內部修改次數檢查,如果檢查到不相等則拋出異常。要避免這種情況的出現則在使用迭代器迭代時(顯示或for-each的隱式)不要使用ArrayList的remove,改爲用Iterator的remove即可。

錯誤二、

public static void main(String[] args){
    ArrayList<Integer> list = new ArrayList<>();
    list.add(1);
    list.add(2);
    list.add(3);
    for(int i=0;i<list.size();i++){
        System.out.println(list.get(i));
    }
}

這裏寫圖片描述
錯誤原因:每刪除一個元素時,它後面的一個元素會向前移一位

    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

        return oldValue;
    }

這種情況可以用倒序刪除來解決。

發佈了35 篇原創文章 · 獲贊 30 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章