ArrayList類詳解與遍歷方式

ArrayList介紹

以下是ArrayList源碼的介紹:

/**
 * Resizable-array implementation of the <tt>List</tt> interface.  Implements
 * all optional list operations, and permits all elements, including
 * <tt>null</tt>. 
 //ArrayList實(shí)現(xiàn)了可變大小的數(shù)組(動態(tài)數(shù)組),它允許所有元素,包括null。
 
 *In addition to implementing the <tt>List</tt> interface,
 * this class provides methods to manipulate the size of the array that is used internally to store the list. 
 //ArrayList實(shí)現(xiàn)了List接口。它提供了一些方法,來操作內(nèi)部用于存儲列表的數(shù)組的大小。
 
 
 *(This class is roughly equivalent to <tt>Vector</tt>, except that it is unsynchronized.)
 //ArrayList同Vector類似,不同的是ArrayList不是同步的。

ArrayList的繼承與接口實(shí)現(xiàn)

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

ArrayList繼承了AbstractList,實(shí)現(xiàn)了List。它提供了相關(guān)的增加、刪除、修改、遍歷等功能。

ArrayList實(shí)現(xiàn)了RandomAccess接口,即提供了隨機(jī)訪問功能。RandomAccess是java中用來被List實(shí)現(xiàn),為List提供快速訪問功能的。

ArrayList實(shí)現(xiàn)了Cloneable接口,即覆蓋了函數(shù)clone(),能被克隆。

ArrayList實(shí)現(xiàn)java.io.Serializable接口,即ArrayList支持序列化,能通過序列化去傳輸。

ArrayList與Collection關(guān)系如下:

image

ArrayList的構(gòu)造器

ArrayList提供了三個構(gòu)造器:

1.public ArrayList(int initialCapacity);
用指定的大小來初始化內(nèi)部的數(shù)組

源碼如下:

    /**
     * Shared empty array instance used for empty instances.
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};
    
    transient Object[] elementData;
    /**
     * Constructs an empty list with the specified initial capacity.
     *
     * @param  initialCapacity  the initial capacity of the list
     * @throws IllegalArgumentException if the specified initial capacity is negative
     */
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
          //若指定的初始容量為負(fù),非法參數(shù)異常
            throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity);
        }
    }

2.public ArrayList();
默認(rèn)的構(gòu)造器,以默認(rèn)大小(10)來初始化內(nèi)部的數(shù)組。

源碼如下:

    /**
     * Default initial capacity.
     */
    private static final int DEFAULT_CAPACITY = 10;
     /**
     * Shared empty array instance used for default sized empty instances. We
     * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
     * first element is added.
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

3.public ArrayList(Collection<? extends E> c);
用一個Collection對象來構(gòu)造,并將集合的元素添加到ArrayList。

源碼如下:

   /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's iterator.
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    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的常用方法:

1.添加方法:

(1) public boolean add(E e)

Appends the specified element to the end of this list.

(2) public void add(int index, E element)

Inserts the specified element at the specified position in this ist.

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

Appends all of the elements in the specified collection to the end of this list,, in the order that they are returned by the specified collection's Iterator.

(4) public boolean addAll(int index, Collection<? extends E> c)

Inserts all of the elements in the specified collection into this
list, starting at the specified position.

2.刪除方法

(1) public E remove(int index)

Removes the element at the specified position in this list.

(2) public boolean remove(Object o)

Removes the first occurrence of the specified element from this list,if it is present.

(3) private void fastRemove(int index)

Private remove method that skips bounds checking and does not return the value removed.

(4) protected void removeRange(int fromIndex, int toIndex)

Removes from this list all of the elements whose index is between {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.

(5) public void clear()

Removes all of the elements from this list.

(6) public boolean removeAll(Collection<?> c)

Removes from this list all of its elements that are contained in the specified collection.

3.修改方法

public E set(int index, E element)

Replaces the element at the specified position in this list with the specified element.

4.獲取元素

public E get(int index)

Returns the element at the specified position in this list.

5.toArray()

(1) public Object[] toArray()

Returns an array containing all of the elements in this list in proper sequence (from first to last element).

(按適當(dāng)順序(從第一個元素到最后一個元素)返回包含此列表中所有元素的數(shù)組。)

(2) public <T> T[] toArray(T[] a)

Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.

(返回?cái)?shù)組的運(yùn)行時類型是指定數(shù)組的運(yùn)行時類型。)

6.trimToSize

public void trimToSize()

Trims the capacity of this <tt>ArrayList</tt> instance to be the list's current size.

這個方法用于將ArrayList固定到實(shí)際元素的大小,當(dāng)動態(tài)數(shù)組元素確定不再添加的時候,可以調(diào)用這個方法來釋放空余的內(nèi)存。

7.其他

(1) public int indexOf(Object o)

Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

(2) public int lastIndexOf(Object o)

Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.

(3) public boolean contains(Object o)

(4) public boolean isEmpty()

(5)public int size()

ArrayList的遍歷方式及效率比較

遍歷ArrayList的方法有如下幾種:

1.Iterator迭代器方式遍歷

(1)Iterator的while實(shí)現(xiàn)

Iterator<Integer> iter=list.iterator();
        while (iter.hasNext()){
            System.out.println(iter.next());
        }

(2)Iterator的for實(shí)現(xiàn)

for (Iterator<Integer> iter = list.iterator(); iter.hasNext(); ) {
            System.out.println(iter.next());
 }

2.隨機(jī)訪問,通過索引值去遍歷get(index)

ArrayList實(shí)現(xiàn)了RandomAccess接口,它支持通過索引值去隨機(jī)訪問元素。

 //基本的for
for (int i = 0; i < list.size(); i++) {
      System.out.println(list.get(i));
}

3.單用foreach語句遍歷

        for (Integer value : list) {
        System.out.println(value);
}

遍歷方式間的比較

ArrayList實(shí)現(xiàn)了RandomAccess隨機(jī)訪問接口,因此它對隨機(jī)訪問的速度快,而基本的for循環(huán)中的get()方法,采用的即是隨機(jī)訪問的方法,因而在ArrayList中,for循環(huán)速度快。

LinkedList采取的是順序訪問方式,iterator中的next()方法,采用的即是順序訪問方法,因此在LinkedList中,使用iterator的速度較快。

for、foreach、iterator的區(qū)別:

(1)條件上:

? for需要知道集合或數(shù)組的大小,還要是有序的,否則無法遍歷。
? foreach和iterator不需要知道集合或數(shù)組大小,他們是得到集合內(nèi)的每個元素后進(jìn)行處理。

(2)多態(tài)上:

? for和foreach都需要先知道集合的類型,甚至是集合內(nèi)元素的類型,不能實(shí)現(xiàn)多態(tài)。
? iterator是個借口類型,不需要關(guān)心所遍歷的序列的類型,能夠?qū)⒈闅v序列的操作與序列底層的結(jié)構(gòu)分離。迭代器統(tǒng)一了對容器的訪問方式。

(3)用法上:

?for循環(huán)一般用來處理比較簡單的有序的,可預(yù)知大小的集合或數(shù)組。

?foreach可用于遍歷任何集合或數(shù)組,但是需要知道集合內(nèi)部類型。

?iterator不需要知道元素和集合的類型,可以隨時修改或者刪除集合內(nèi)部的元素。當(dāng)需要對不同的容器實(shí)現(xiàn)同樣的遍歷方式時,可用迭代器。

總結(jié)起來,就是for需要知道大??;foreach需要知道類型;iterator既不需要知道大小,也不需要知道類型。

相關(guān)推薦:

ArrayList擴(kuò)容分析

參考資料:

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

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容