文章目錄
概述
從類的繼承圖上我們可知道,ArrayList實現了List接口。
-
同時List是順序容器,即元素存放的數據與放進去的順序相同,允許放入null元素,
-
ArrayList底層基于數組實現。
-
每個ArrayList都有一個容量(capacity),表示底層數組的實際大小,容器內存儲元素的個數不能多于當前容量。
-
當向容器中添加元素時,如果容量不足,容器自動擴容。
-
ArrayList<E>
,可以看到是泛型類型, Java泛型只是編譯器提供的語法糖,數組是一個Object數組,可以容納任何類型的對象。
方法的執(zhí)行效率
-
size(), isEmpty(), get(), set()
方法均能在常數時間內完成 -
add()
方法的時間開銷跟插入位置有關 -
addAll()
方法的時間開銷跟添加元素的個數成正比。 - 其余方法大都是線性時間。
為追求效率,ArrayList沒有實現同步(synchronized),如果需要多個線程并發(fā)訪問,用戶可以手動同步,也可使用Vector替代
源碼剖析
底層數據結構 -數組
構造函數
/**
* 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 {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
* 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) {
Object[] a = c.toArray();
if ((size = a.length) != 0) {
if (c.getClass() == ArrayList.class) {
elementData = a;
} else {
elementData = Arrays.copyOf(a, size, Object[].class);
}
} else {
// replace with empty array.
elementData = EMPTY_ELEMENTDATA;
}
}
演示如下:
/**
* 初始化的時候指定容量
*/
List list = new ArrayList<>(1);
list.add(1);
list.add(2);
System.out.println(list.size());
/**
* 默認構造函數 ,數組大小為0
*/
list = new ArrayList();
list.add("artisan");
list.add("review");
list.add("java");
System.out.println(list.size());
/**
* 使用集合初始化一個ArrayList
*/
list = new ArrayList(Arrays.asList("I" , "Love" ,"Code"));
System.out.println(list.size());
自動擴容機制
-
每當向數組中添加元素時,都需要檢查添加后元素的個數是否會超出當前數組的長度,如果超出,數組將會進行擴容,以滿足添加數據的需求。
-
數組進行擴容時,會將老數組中的元素重新拷貝一份到新的數組中,每次數組容量的增長大約是其原容量的1.5倍。
這種操作的代價是很高的,因此在實際使用時,我們應該盡量避免數組容量的擴張。當我們可預知要保存的元素的多少時,要在構造ArrayList實例時,就指定其容量,以避免數組擴容的發(fā)生。
或者根據實際需求,通過調用ensureCapacity方法來手動增加ArrayList實例的容量。
ArrayList#ensureCapacity(int minCapacity)
暴漏了public方法可以允許程序猿手工擴容增加ArrayList實例的容量,以減少遞增式再分配的數量。
我們來看下效率對比
/**
* 擴容對比
*/
long begin = System.currentTimeMillis();
// 初始化1億的數據量
final int number = 100000000 ;
Object o = new Object();
ArrayList list1 = new ArrayList<String>();
for (int i = 0; i < number; i++) {
list1.add(o);
}
System.out.println("依賴ArrayList的自動擴容機制,添加數據耗時:" +(System.currentTimeMillis() - begin));
begin = System.currentTimeMillis();
ArrayList list2 = new ArrayList<String>();
// 手工擴容
list2.ensureCapacity(number);
for (int i = 0; i < number; i++) {
list2.add(o);
}
System.out.println("手工ensureCapacity擴容后,添加數據耗時:" + (System.currentTimeMillis() - begin));
原因是因為,第一段如果沒有一次性擴到想要的最大容量的話,它就會在添加元素的過程中,一點一點的進行擴容,要知道對數組擴容是要進行數組拷貝的,這就會浪費大量的時間。如果已經預知容器可能會裝多少元素,最好顯示的調用ensureCapacity這個方法一次性擴容到位。
過程圖如下:
set()
底層是一個數組, 那ArrayList的set()方法也就是直接對數組的指定位置賦值
/**
* Replaces the element at the specified position in this list with
* the specified element.
*
* @param index index of the element to replace
* @param element element to be stored at the specified position
* @return the element previously at the specified position
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
get
get()方法也很簡單,需要注意的是由于底層數組是Object[],得到元素后需要進行類型轉換。
/**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
add()/addAll()
這兩個方法都是向容器中添加新元素,這可能會導致capacity不足,因此在添加元素之前,都需要進行剩余空間檢查,如果需要則自動擴容。擴容操作最終是通過grow()方法完成的
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
/**
* Inserts the specified element at the specified position in this
* list. Shifts the element currently at that position (if any) and
* any subsequent elements to the right (adds one to their indices).
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
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++;
}
- add(E e) 在末尾添加
- add(int index, E e)需要先對元素進行移動,然后完成插入操作,也就意味著該方法有著線性的時間復雜度。
-
addAll()方法能夠一次添加多個元素,根據位置不同也有兩個把本
一個是在末尾添加的
addAll(Collection<? extends E> c)
方法,一個是從指定位置開始插入的
addAll(int index, Collection<? extends E> c)
方法。跟add()方法類似,在插入之前也需要進行空間檢查,如果需要則自動擴容;如果從指定位置插入,也會存在移動元素的情況。]
addAll()的時間復雜度不僅跟插入元素的多少有關,也跟插入的位置相關。
/**
* 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. The behavior of this operation is
* undefined if the specified collection is modified while the operation
* is in progress. (This implies that the behavior of this call is
* undefined if the specified collection is this list, and this
* list is nonempty.)
*
* @param c collection containing elements to be added to this list
* @return <tt>true</tt> if this list changed as a result of the call
* @throws NullPointerException if the specified collection is null
*/
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;
}
/**
* Inserts all of the elements in the specified collection into this
* list, starting at the specified position. Shifts the element
* currently at that position (if any) and any subsequent elements to
* the right (increases their indices). The new elements will appear
* in the list in the order that they are returned by the
* specified collection's iterator.
*
* @param index index at which to insert the first element from the
* specified collection
* @param c collection containing elements to be added to this list
* @return <tt>true</tt> if this list changed as a result of the call
* @throws IndexOutOfBoundsException {@inheritDoc}
* @throws NullPointerException if the specified collection is null
*/
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;
}
remove()
remove()方法也有兩個方法
- 一個是remove(int index)刪除指定位置的元素
- 一個是remove(Object o)刪除第一個滿足o.equals(elementData[index])的元素
/**
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*
* @param index the index of the element to be removed
* @return the element that was removed from the list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
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;
}
刪除操作是add()操作的逆過程,需要將刪除點之后的元素向前移動一個位置。需要注意的是為了讓GC起作用,必須顯式的為最后一個位置賦null值。
上面代碼中如果不手動賦null值,除非對應的位置被其他元素覆蓋,否則原來的對象就一直不會被回收。
/**
* Removes the first occurrence of the specified element from this list,
* if it is present. If the list does not contain the element, it is
* unchanged. More formally, removes the element with the lowest index
* <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
* (if such an element exists). Returns <tt>true</tt> if this list
* contained the specified element (or equivalently, if this list
* changed as a result of the call).
*
* @param o element to be removed from this list, if present
* @return <tt>true</tt> if this list contained the specified element
*/
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;
}
trimToSize()
將底層數組的容量調整為當前列表保存的實際元素的大小
/**
* Trims the capacity of this <tt>ArrayList</tt> instance to be the
* list's current size. An application can use this operation to minimize
* the storage of an <tt>ArrayList</tt> instance.
*/
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
indexOf(), lastIndexOf()
獲取元素的第一次出現的index
/**
* Returns the index of the first occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the lowest index <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*/
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;
}
獲取元素的最后一次出現的index
/**
* Returns the index of the last occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the highest index <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*/
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;
}
Fail-Fast
ArrayList同樣采用了快速失敗的機制,通過記錄modCount參數來實現。在面對并發(fā)的修改時,迭代器很快就會完全失敗,而不是冒著在將來某個不確定時間發(fā)生任意不確定行為的風險。
具體參考前段時間寫的一篇博文如下:
本文摘自 :https://blog.51cto.com/u