ArrayList是java集合框架中比較經常使用的數據結構,其實底層就是一個數組的操做實現,可是這個數組呢能夠實現容量大小的動態變化,這就是比較特別的地方吧。另外ArrayList不是線程安全的。java
從圖中能夠看出ArrayList類繼承了AbstractList類,實現了List、RandomAccess、Serialzable、Cloneable接口數組
實現RandomAccess接口:能夠經過下標序號快速訪問
實現了Cloneable,能被克隆
實現了Serializable,支持序列化
複製代碼
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 = {};
transient Object[] elementData; // non-private to simplify nested class access
private int size;
...
}
複製代碼
/**
* 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);
}
}
複製代碼
指定初始化長度,固然這個初始化容量長度不能小於0,若是等於0,則賦一個空集合EMPTY_ELEMENTDATA。安全
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
複製代碼
這是最經常使用的默認構造方法,其中使用默認的初始容量大小10,並賦予一個空數組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) {
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;
}
}
複製代碼
使用已有集合來建立ArraList,將集合裏的值複製到ArrayList中。首先把集合轉換成數組,而後判斷轉換的數組類型是否爲Obejct[]類型,若是是則將數組的值拷貝到list中,不然或者容量爲0,則賦予一個空數組框架
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
//擴容以後再添加元素
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
//計算容量
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
//新容量爲原來容量的二分之三倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
//新容量小於須要擴容的容量
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
//新容量大於數組能申請的最大值 MAX_ARRAY_SIZE=Integer.MAX_VALUE - 8
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
//擴容成功移動數據
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;
}
複製代碼
size表示ArrayList的元素個數。在添加元素以前先要確保數組有足夠容量。噹噹前數組須要的空間不夠時,就須要擴容了,而且保證新容量不能比當前須要的容量小,而後調Arrays.copyOf()建立一個新的數組並將數據拷貝到新數組中,且把引用賦值給elementDatadom
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++;
}
複製代碼
指定數組index位置添加元素。首先會檢查index是否超出數組的範圍;而後既然要添加元素,就要保證有足夠的數組空間;固然要在index位置插入元素,得讓index後全部的元素日後移動一位,騰出index位置設置要添加的元素。ide
添加元素時,都涉及到了對數組的複製移動,用到了兩種方法函數
Arrays.copyOf(elementData, newCapacity);
System.arraycopy(elementData, index, elementData, index + 1,size - index);
複製代碼
第一個方法是生成一個一樣大小的新對象,固然底層也是使用了System.arraycopy方法ui
public static native void arraycopy(Object src, int srcPos,Object dest, int destPos,int length);
複製代碼
第二個方法是將數組複製到指定數組中,還能夠選擇複製數組的長度。使用arraycopy方法 本身複製本身,將數組要放置的地方的對象移到後面去this
實質上都是底層clone來的結果
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;
}
複製代碼
刪除指定位置的元素。首先也是檢查index的合法性,而後取得該位置的舊元素,計算須要移動的長度,若是須要移動的,則調用System.arraycopy方法將index位置後的元素全部往前移動一位,將數組最後一位置爲null,方便GC工做,最後返回被刪除的元素。
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
}
複製代碼
刪除指定元素,這裏刪除的是數組中第一個找到的元素。fastRemove方法移除,這裏沒有進行index範圍檢查
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
E elementData(int index) {
return (E) elementData[index];
}
複製代碼
獲取指定index位置的元素。這個實現很簡單,首先index範圍檢查,而後直接取數組中index位置元素返回。
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
複製代碼
修改指定位置的元素,並返回舊值
使用集合的都知道,在for循環遍歷集合時不能夠對集合進行刪除操做,由於刪除會致使集合大小改變,從而致使數組遍歷時數組下標越界,嚴重時會拋ConcurrentModificationException異常
使用迭代器遍歷刪除,運行正常
public Iterator<E> iterator() {
return new Itr();
}
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
Itr() {}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
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];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
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();
}
}
複製代碼
從代碼中能夠看出iterator方法返回的是一個Itr()對象。
Itr對象有三個成員變量:
cursor:表明下一個要訪問的數組下標
lastRet:表明上一個要訪問的數組下標
expectedModCount:表明ArrayList修改次數的指望值,初始爲modeCount
複製代碼
Itr有三個主要函數:
hasNext:實現簡單,判斷下一個要訪問的數組下標等於數組大小,表示遍歷到最後了
next:首先判斷 expectedModCount 和 modCount 是否相等。每調用一次 next 方法, cursor 和 lastRet 都會自增 1。
remove :首先會判斷 lastRet 的值是否小於 0,而後在檢查 expectedModCount 和 modCount 是否相等。而後直接調用 ArrayList 的 remove 方法刪除下標爲 lastRet 的元素。而後將 lastRet 賦值給 cursor ,將 lastRet 從新賦值爲 -1,並將 modCount 從新賦值給 expectedModCount。
複製代碼
remove方法弊端:
調用 remove 以前必須先調用 next。由於 remove 開始就對 lastRet 作了校驗。而 lastRet 初始化時爲 -1。
next 以後只能夠調用一次 remove。由於 remove 會將 lastRet 從新初始化爲 -1
複製代碼
ArrayList是一個能夠自動擴容的動態數組。
ArrayList的默認容量大小是10
擴容爲原來的1.5倍,若是1.5倍還不夠的話,直接擴容成咱們所須要的容量,1.5倍或所需容量太大的話,直接擴容成Integer.MAX_VALUE或MAX_ARRAY_SIZE
擴容以後經過數組拷貝確保元素的準確性,儘可能減小擴容機制
複製和擴容使用了Arrays.copyOf和System.arraycopy方法
ArrayList查找效率高,插入刪除操做效率相對低
size 爲集合實際存儲元素個數
elementData.length 爲數組長度,表示數組能夠存儲多少個元素
若是須要邊遍歷邊 remove ,必須使用 iterator。且 remove 以前必須先 next,next 以後只能用一次 remove。