Jdk源碼之ArrayList

 

1. ArrayList簡介

首先看看ArrayList與Collection的關係:java

java集合框架03——ArrayList和源碼分析

ArrayList的繼承關係以下:數組

java.lang.Object ↳ java.util.AbstractCollection

ArrayList繼承了AbstractList,實現了List。它是一個數組隊列,至關於動態數組。提供了相關的添加、刪除、修改和遍歷等功能。安全

ArrayList實現了RandomAccess接口,即提供了隨機訪問功能。RandomAccess是java中用來被List實現,爲List提供快速訪問功能的。在ArrayList中,咱們便可以經過元素的序號來快速獲取元素對象,這就是快速隨機訪問。下文會比較List的「快速隨機訪問」和使用「Iterator迭代器訪問」的效率。多線程

ArrayList實現了Cloneable接口,即覆蓋了函數clone,能被克隆。app

ArrayList實現了java.io.Serializable接口,這意味着ArrayList支持序列化,能經過序列化去傳輸。框架

和Vector不一樣,ArrayList中的操做是非線程安全的。因此建議在單線程中使用ArrayList,在多線程中選擇Vector或者CopyOnWriteArrayList。dom

咱們先總覽下ArrayList的構造函數和API:函數

/****************** ArrayList中的構造函數 ***************/ 
// 默認構造函數 ArrayList 
// capacity是ArrayList的默認容量大小。當因爲增長數據致使容量不足時,容量會添加上一次容量大小的一半。 
ArrayList(int capacity) 

// 建立一個包含collection的ArrayList 
ArrayList(Collection extends E> collection) 

/****************** ArrayList中的API ********************/ 
// Collection中定義的API
boolean             add(E object)
boolean             addAll(Collection<? extends E> collection)
void                clear()
boolean             contains(Object object)
boolean             containsAll(Collection<?> collection)
boolean             equals(Object object)
int                 hashCode()
boolean             isEmpty()
Iterator<E>         iterator()
boolean             remove(Object object)
boolean             removeAll(Collection<?> collection)
boolean             retainAll(Collection<?> collection)
int                 size()
<T> T[]             toArray(T[] array)
Object[]            toArray()
// AbstractCollection中定義的API
void                add(int location, E object)
boolean             addAll(int location, Collection<? extends E> collection)
E                   get(int location)
int                 indexOf(Object object)
int                 lastIndexOf(Object object)
ListIterator<E>     listIterator(int location)
ListIterator<E>     listIterator()
E                   remove(int location)
E                   set(int location, E object)
List<E>             subList(int start, int end)
// ArrayList新增的API
Object               clone()
void                 ensureCapacity(int minimumCapacity)
void                 trimToSize()
void                 removeRange(int fromIndex, int toIndex)

ArrayList包含了兩個重要的對象:elementData和size。源碼分析

elementData是Object類型的數組,它保存了添加到ArrayList中的元素。實際上,elementData是一個動態數組,咱們能經過ArrayList(int initialCapacity)來執行它的初始容量爲initialCapacity。若是經過不含參數的構造函數來建立ArrayList,則elementData是一個空數組(後面會調整其大小)。elementData數組的大小會根據ArrayList容量的增加而動態的增加,具體見下面的源碼。測試

size則是動態數組實際的大小。

2. ArrayList源碼分析

下面經過分析ArrayList的源碼更加深刻的瞭解ArrayList原理。因爲ArrayList是經過數組實現的,因此源碼比較容易理解:

package java.util;
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    // 序列版本號
    private static final long serialVersionUID = 8683452581122892189L;
    // 保存ArrayList中數據的數組
    private transient Object[] elementData;
    // ArrayList中實際數據的數量
    private int size;
    // ArrayList帶容量大小的構造函數。
    public ArrayList(int initialCapacity) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        // 新建一個數組
        this.elementData = new Object[initialCapacity];
    }
    // ArrayList構造函數。默認容量是10。
    public ArrayList() {
        this(10);
    }
    // 建立一個包含collection的ArrayList
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        size = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    }
    // 將當前容量值設爲 =實際元素個數
    public void trimToSize() {
        modCount++;
        int oldCapacity = elementData.length;
        if (size < oldCapacity) {
            elementData = Arrays.copyOf(elementData, size);
        }
    }
    // 肯定ArrarList的容量。
    // 若ArrayList的容量不足以容納當前的所有元素,設置 新的容量=「(原始容量x3)/2 + 1」
    public void ensureCapacity(int minCapacity) {
        // 將「修改統計數」+1
        modCount++;
        int oldCapacity = elementData.length;
        // 若當前容量不足以容納當前的元素個數,設置 新的容量=「(原始容量x3)/2 + 1」
        if (minCapacity > oldCapacity) {
            Object oldData[] = elementData;
            int newCapacity = (oldCapacity * 3)/2 + 1;
            if (newCapacity < minCapacity)
                newCapacity = minCapacity;
            elementData = Arrays.copyOf(elementData, newCapacity);
        }
    }
    // 添加元素e
    public boolean add(E e) {
        // 肯定ArrayList的容量大小
        ensureCapacity(size + 1);  // Increments modCount!!
        // 添加e到ArrayList中
        elementData[size++] = e;
        return true;
    }
    // 返回ArrayList的實際大小
    public int size() {
        return size;
    }
    // 返回ArrayList是否包含Object(o)
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }
    // 返回ArrayList是否爲空
    public boolean isEmpty() {
        return size == 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;
    }
    // 反向查找(從數組末尾向開始查找),返回元素(o)的索引值
    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;
    }

    // 返回ArrayList的Object數組
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }
    // 返回ArrayList的模板數組。所謂模板數組,便可以將T設爲任意的數據類型
    public <T> T[] toArray(T[] a) {
        // 若數組a的大小 < ArrayList的元素個數;
        // 則新建一個T[]數組,數組大小是「ArrayList的元素個數」,並將「ArrayList」所有拷貝到新數組中
        if (a.length < size)
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        // 若數組a的大小 >= ArrayList的元素個數;
        // 則將ArrayList的所有元素都拷貝到數組a中。
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }
    // 獲取index位置的元素值
    public E get(int index) {
        RangeCheck(index);
        return (E) elementData[index];
    }
    // 設置index位置的值爲element
    public E set(int index, E element) {
        RangeCheck(index);
        E oldValue = (E) elementData[index];
        elementData[index] = element;
        return oldValue;
    }
    // 將e添加到ArrayList中
    public boolean add(E e) {
        ensureCapacity(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    // 將e添加到ArrayList的指定位置
    public void add(int index, E element) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(
            "Index: "+index+", Size: "+size);
        ensureCapacity(size+1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
             size - index);
        elementData[index] = element;
        size++;
    }
    // 刪除ArrayList指定位置的元素
    public E remove(int index) {
        RangeCheck(index);
        modCount++;
        E oldValue = (E) elementData[index];
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                 numMoved);
        elementData[--size] = null; // 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;
    }
    // 快速刪除第index個元素
    private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        // 從"index+1"開始,用後面的元素替換前面的元素。
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        // 將最後一個元素設爲null
        elementData[--size] = null; // Let gc do its work
    }
    // 刪除元素
    public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
            if (elementData[index] == null) {
                fastRemove(index);
            return true;
            }
        } else {
            // 便利ArrayList,找到「元素o」,則刪除,並返回true。
            for (int index = 0; index < size; index++)
            if (o.equals(elementData[index])) {
                fastRemove(index);
            return true;
            }
        }
        return false;
    }
    // 清空ArrayList,將所有的元素設爲null
    public void clear() {
        modCount++;
        for (int i = 0; i < size; i++)
            elementData[i] = null;
        size = 0;
    }
    // 將集合c追加到ArrayList中
    public boolean addAll(Collection<? extends E> c) {
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacity(size + numNew);  // Increments modCount
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
        return numNew != 0;
    }
    // 從index位置開始,將集合c添加到ArrayList
    public boolean addAll(int index, Collection<? extends E> c) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(
            "Index: " + index + ", Size: " + size);
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacity(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之間的所有元素。
    protected void removeRange(int fromIndex, int toIndex) {
    modCount++;
    int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);
    // Let gc do its work
    int newSize = size - (toIndex-fromIndex);
    while (size != newSize)
        elementData[--size] = null;
    }
    private void RangeCheck(int index) {
    if (index >= size)
        throw new IndexOutOfBoundsException(
        "Index: "+index+", Size: "+size);
    }
    // 克隆函數
    public Object clone() {
        try {
            ArrayList<E> v = (ArrayList<E>) super.clone();
            // 將當前ArrayList的所有元素拷貝到v中
            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();
        }
    }
    // java.io.Serializable的寫入函數
    // 將ArrayList的「容量,全部的元素值」都寫入到輸出流中
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
    // Write out element count, and any hidden stuff
    int expectedModCount = modCount;
    s.defaultWriteObject();
        // 寫入「數組的容量」
        s.writeInt(elementData.length);
    // 寫入「數組的每個元素」
    for (int i=0; i<size; i++)
            s.writeObject(elementData[i]);
    if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }
    // java.io.Serializable的讀取函數:根據寫入方式讀出
    // 先將ArrayList的「容量」讀出,而後將「全部的元素值」讀出
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        // Read in size, and any hidden stuff
        s.defaultReadObject();
        // 從輸入流中讀取ArrayList的「容量」
        int arrayLength = s.readInt();
        Object[] a = elementData = new Object[arrayLength];
        // 從輸入流中將「全部的元素值」讀出
        for (int i=0; i<size; i++)
            a[i] = s.readObject();
    }
}

總結一下:

1). ArrayList其實是經過一個數組去保存數據的,當咱們構造ArrayList時,若是使用默認構造函數,最後ArrayList的默認容量大小是10。

2). 當ArrayList容量不足以容納所有元素時,ArrayList會自動擴張容量,新的容量 = 原始容量 + 原始容量 / 2。

3). ArrayList的克隆函數,便是將所有元素克隆到一個數組中。

4. ArrayList實現java.io.Serializable的方式。當寫入到輸出流時,先寫入「容量」,再依次寫出「每個元素」;當讀出輸入流時,先讀取「容量」,再依次讀取「每個元素」。

3. ArrayList遍歷方式

ArrayList支持三種遍歷方式,下面咱們逐個討論:

1). 經過迭代器遍歷。即Iterator迭代器。

Integer value = null; 
Iterator it = list.iterator; 
while (it.hasNext) { 
    value = (Integer)it.next; 
​​​​​​​}

2). 隨機訪問,經過索引值去遍歷。因爲ArrayList實現了RandomAccess接口,因此它支持經過索引值去隨機訪問元素。

Integer value = null;
int size = list.size();
for (int i=0; i<size; i++) {
    value = (Integer)list.get(i);        
}

3)for循環遍歷

Integer value = null;
for (Integer integ:list) {
    value = integ;
}

下面寫了一個測試用例,比較這三種遍歷方式的效率:

import java.util.*;
import java.util.concurrent.*;
/*
 * @desc ArrayList遍歷方式和效率的測試程序。
 *
 * @author skywang
 */
public class ArrayListRandomAccessTest {
    public static void main(String[] args) {
        List list = new ArrayList();
        for (int i=0; i<100000; i++)
            list.add(i);
        //isRandomAccessSupported(list);
        iteratorThroughRandomAccess(list) ;
        iteratorThroughIterator(list) ;
        iteratorThroughFor2(list) ;

    }
    private static void isRandomAccessSupported(List list) {
        if (list instanceof RandomAccess) {
            System.out.println("RandomAccess implemented!");
        } else {
            System.out.println("RandomAccess not implemented!");
        }
    }
    public static void iteratorThroughRandomAccess(List list) {
        long startTime;
        long endTime;
        startTime = System.currentTimeMillis();
        for (int i=0; i<list.size(); i++) {
            list.get(i);
        }
        endTime = System.currentTimeMillis();
        long interval = endTime - startTime;
        System.out.println("iteratorThroughRandomAccess:" + interval+" ms");
    }
    public static void iteratorThroughIterator(List list) {
        long startTime;
        long endTime;
        startTime = System.currentTimeMillis();
        for(Iterator iter = list.iterator(); iter.hasNext(); ) {
            iter.next();
        }
        endTime = System.currentTimeMillis();
        long interval = endTime - startTime;
        System.out.println("iteratorThroughIterator:" + interval+" ms");
    }
    public static void iteratorThroughFor2(List list) {
        long startTime;
        long endTime;
        startTime = System.currentTimeMillis();
        for(Object obj:list)

        endTime = System.currentTimeMillis();
        long interval = endTime - startTime;
        System.out.println("iteratorThroughFor2:" + interval+" ms");
    }
}

運行結果:


iteratorThroughRandomAccess:3 ms
iteratorThroughIterator:8 ms
iteratorThroughFor2:5 ms


因而可知,遍歷ArrayList時,使用隨機訪問(即,經過索引序號訪問)效率最高,而使用迭代器的效率最低!

4. toArray異常問題

當咱們調用ArrayList中的 toArray(),可能遇到過拋出「java.lang.ClassCastException」異常的狀況。下面咱們說說這是怎麼回事。
ArrayList提供了2個toArray()函數:
Object[] toArray()
<T> T[] toArray(T[] contents)
調用 toArray() 函數會拋出「java.lang.ClassCastException」異常,可是調用 toArray(T[] contents) 能正常返回 T[]。
toArray() 會拋出異常是由於 toArray() 返回的是 Object[] 數組,將 Object[] 轉換爲其它類型(如如,將Object[]轉換爲的Integer[])則會拋出「java.lang.ClassCastException」異常,由於Java不支持向下轉型。具體的能夠參考前面ArrayList.java的源碼介紹部分的toArray()。
解決該問題的辦法是調用 <T> T[] toArray(T[] contents) , 而不是 Object[] toArray()。
調用 toArray(T[] contents) 返回T[]的能夠經過如下幾種方式實現。

// toArray(T[] contents)調用方式一
public static Integer[] vectorToArray1(ArrayList<Integer> v) {
    Integer[] newText = new Integer[v.size()];
    v.toArray(newText);
    return newText;
}
// toArray(T[] contents)調用方式二。最經常使用!
public static Integer[] vectorToArray2(ArrayList<Integer> v) {
    Integer[] newText = (Integer[])v.toArray(new Integer[0]);
    return newText;
}
// toArray(T[] contents)調用方式三
public static Integer[] vectorToArray3(ArrayList<Integer> v) {
    Integer[] newText = new Integer[v.size()];
    Integer[] newStrings = (Integer[])v.toArray(newText);
    return newStrings;
}

五、 ArrayList示例
 

 

public class ArrayListTest {
    public static void main(String[] args) {

        // 建立ArrayList
        ArrayList list = new ArrayList();
        // 將「」
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
        // 將下面的元素添加到第1個位置
        list.add(0, "5");
        // 獲取第1個元素
        System.out.println("the first element is: "+ list.get(0));
        // 刪除「3」
        list.remove("3");
        // 獲取ArrayList的大小
        System.out.println("Arraylist size=: "+ list.size());
        // 判斷list中是否包含"3"
        System.out.println("ArrayList contains 3 is: "+ list.contains(3));
        // 設置第2個元素爲10
        list.set(1, "10");
        // 經過Iterator遍歷ArrayList
        for(Iterator iter = list.iterator(); iter.hasNext(); ) {
            System.out.println("next is: "+ iter.next());
        }
        // 將ArrayList轉換爲數組
        String[] arr = (String[])list.toArray(new String[0]);
        for (String str:arr)
            System.out.println("str: "+ str);
        // 清空ArrayList
        list.clear();
        // 判斷ArrayList是否爲空
        System.out.println("ArrayList is empty: "+ list.isEmpty());
    }
}

 ArrayList remove容易出現的錯誤

在項目開發中,咱們可能每每須要動態的刪除ArrayList中的一些元素。 一種錯誤的方式:

<!-- lang: java -->
for(int i = 0 , len= list.size();i<len;++i){
  if(list.get(i)==XXX){
   list.remove(i);
  }
}

上面這種方式會拋出以下異常:

<!-- lang: java -->
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
at java.util.ArrayList.RangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at ListDemo.main(ListDemo.java:20)

由於你刪除了元素,可是未改變迭代的下標,這樣當迭代到最後一個的時候就會拋異常咯。

能夠對上面的程序進行以下改進:

<!-- lang: java -->
for(int i = 0 , len= list.size();i<len;++i){
  if(list.get(i)==XXX){
       list.remove(i);
       --len;//減小一個
       --i;//回退一個
     }
}

上面的代碼就正確了。

下面咱們再介紹一種方案:

List接口內部實現了Iterator接口,提供開發者一個iterator()獲得當前list對象的一個iterator對象。

<!-- lang: java -->
    Iterator<String> sListIterator = list.iterator();
while(sListIterator.hasNext()){
    String e = sListIterator.next();
    if(e.equals("3")){
    sListIterator.remove();
    }
}

上面這種也是正確的,並推薦使用第二種方案。

兩種方案實現原理都差多的,第二種只是jdk封裝了下。

查看ArrayList源碼會發現不少方法內部都是基於iterator接口實現的,因此推薦使用第二種方案。

相關文章
相關標籤/搜索