數組指的就是一組相關類型的變量集合,而且這些變量能夠按照統一的方式進行操做,數組數據引用數據類型,在堆中進行內存分配,在內存中是連續存在,大小固定的。java
ArrayList能夠算是數組的增強版,其繼承AbstractList接口,實現了List,RandomAccess,Cloneable接口,可序列化。在存儲方面 數組能夠包含基本類型和對象類型,好比:int[],Object[],ArrayList只能包含對象類型;在空間方面,數組的空間大小是固定的,空間不夠時不能再次申請,因此須要事前肯定合適的空間大小。ArrayList的空間是動態增加的,若是空間不足,它會建立一個1.5倍大的新數組,而後把全部元素複製到新數組,並且每次添加新的元素時會檢測內部數組的空間是否足夠。數組
//默認初始容量
private static final int DEFAULT_CAPACITY = 10;
//空數組
private static final Object[] EMPTY_ELEMENTDATA = {};
//空數組與EMPTY_ELEMENTDATA 區別在於添加第一個元素時,擴充多少
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
//實例數組對象
transient Object[] elementData; // non-private to simplify nested class access
//數組大小
private int size;
複製代碼
ArrayList的構造方法有三種:bash
//自定義初始容量
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
//初始化容量大小
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
//容量初始值不能 < 0 小於零會拋出異常
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
//經常使用無參構造函數,默認數組大小爲 10
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
//建立一個包含collection的ArrayList
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)
//構造大小爲size的Object[]數組賦值給elementData
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// 替換空數組
this.elementData = EMPTY_ELEMENTDATA;
}
}
複製代碼
ArrayList調用add()方法添加函數,源碼爲併發
//在數組尾部添加元素
public boolean add(E e) {
//長度+1,也就是修改次數+1 確保內部容量
ensureCapacityInternal(size + 1); // Increments modCount!!
//數組下標+1 並賦值
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
//若數組元素爲空,取最小容量,與默認容量的最大值作爲最小容量
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
//明確ArrayList的最小容量
ensureExplicitCapacity(minCapacity);
}
//用於內部優化確保空間資源不被浪費
private void ensureExplicitCapacity(int minCapacity) {
//修改統計數+1,主要用來實現fail-fast機制
modCount++;
// 防止溢出,保證最小容量 > 數組緩衝區當前長度
if (minCapacity - elementData.length > 0)
//增長容量
grow(minCapacity);
}
複製代碼
//增長容量以確保它至少能夠容納最小容量參數指定的元素數量。
private void grow(int minCapacity) {
// 元素長度爲舊容量大小
int oldCapacity = elementData.length;
// 新容量= 舊容量 + 舊容量右移一位(舊容量/2)
int newCapacity = oldCapacity + (oldCapacity >> 1);
//判斷新容量與最小容量大小
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) {
//若最小容量 < 0 則拋出異常
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
//最小容量大於 最大數組長度,則返回int最大值做爲容量大小
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
複製代碼
查看複製數組方法dom
Arrays.copyOf(elementData, newCapacity)
//Arrays.java類中的方法
public static <T> T[] copyOf(T[] original, int newLength) {
return (T[]) copyOf(original, newLength, original.getClass());
//複製指定的數組,截斷或使用null填充(若是須要),以便副本具備指定的長度。
// 對於在原始數組和副本中均有效的全部索引,兩個數組將包含相同的值
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
//從指定的源數組開始複製數組,從指定的位置開始到目標數組的指定位置
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
//內部調用System.arraycopy方法
@FastNative
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
複製代碼
在對應下標出添加數據元素
public void add(int index, E element) {
//超出數據長度或 小於0 ,則拋出數組越界異常
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
///增長容量以確保它至少能夠容納最小容量參數指定的元素數量,修改次數+1
ensureCapacityInternal(size + 1); // Increments modCount!!
//數組拷貝賦值
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
//添加數組集合
public boolean addAll(Collection<? extends E> c) {
//轉化數據
Object[] a = c.toArray();
int numNew = a.length;
//修改次數+1
ensureCapacityInternal(size + numNew); // Increments modCount
//數組拷貝賦值
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
複製代碼
經過分析add方法能夠發現ArrayList內部是調用System.arraycopy方法複製數組。函數
//對應下標設置對應的數組元素,原來的元素被替換掉並返回替換的數組元素
public E set(int index, E element) {
//下標 >數組長度, 則拋出數組越界異常
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
//查找索引對應數組元素
E oldValue = (E) elementData[index];
//數組元素從新賦值
elementData[index] = element;
return oldValue;
}
複製代碼
public E get(int index) {
//下標 >數組長度, 則拋出數組越界異常
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
//根據下標直接返回對應數組元素,查找速度快
return (E) elementData[index];
}
複製代碼
//移除數組下標對應的數組元素,返回刪除的數組元素
public E remove(int index) {
//下標 >數組長度, 則拋出數組越界異常
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
//修改次數統計 +1
modCount++;
//經過索引下標查找對應數組元素
E oldValue = (E) elementData[index];
//數組移動個數
int numMoved = size - index - 1;
if (numMoved > 0)
//後續數組元素總體往前移動
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
//數組最後一位元素置空,且長度-1
elementData[--size] = null; // clear to let GC do its work
//返回移除對應數組元素
return oldValue;
}
複製代碼
//刪除對應元素,若是刪除成功返回true
public boolean remove(Object o) {
if (o == null) { //判斷是否爲空
for (int index = 0; index < size; index++)
if (elementData[index] == null) { //若數組下標對應元素爲空則移除null元素
fastRemove(index);
return true;
}
} else {//不爲空
for (int index = 0; index < size; index++)
//判斷要刪除的對象在數組是否存在,存在則刪除
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
//私有方法快速刪除數組元素,該方法與remove(int index)方法相似
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 int indexOf(Object o) {
if (o == null) { //判斷是否爲空
for (int i = 0; i < size; i++)//遍歷
//數組元素爲null返回對應下標
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
//遍歷存在對象o 則返回對應下標
if (o.equals(elementData[i]))
return i;
}
//數組中不存在,則返回-1
return -1;
}
複製代碼
//從ArrayList中截取子列表集合
public List<E> subList(int fromIndex, int toIndex) {
//子列表集合範圍檢測
subListRangeCheck(fromIndex, toIndex, size);
//返回值爲一個SubList對象
return new SubList(this, 0, fromIndex, toIndex);
}
複製代碼
SubList爲ArrayList的一個內部類源碼分析
private class SubList extends AbstractList<E> implements RandomAccess {
private final AbstractList<E> parent;
private final int parentOffset;
private final int offset;
int size;
SubList(AbstractList<E> parent,
int offset, int fromIndex, int toIndex) {
//該參數爲父類ArrayList 把自身傳了進來
this.parent = parent;
//開始截取的位置索引
this.parentOffset = fromIndex;
this.offset = offset + fromIndex;
//截取後獲得的ArrayList長度
this.size = toIndex - fromIndex;
this.modCount = ArrayList.this.modCount;
}
public void add(int index, E e) {
//檢測索引是否越界,越界則拋出異常
rangeCheckForAdd(index);
//檢測數組列表是否被修改
checkForComodification();
parent.add(parentOffset + index, e);
this.modCount = parent.modCount;
this.size++;
}
private void checkForComodification() {
//判斷ArrayList的修改次數與子類的修改次數是否相等,不然拋出併發修改異常
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
}
.....
}
複製代碼
舉個例子:post
ArrayList<String> list = new ArrayList<>();
list.add("f1");
list.add("f2");
list.add("f3");
List<String> subList =list.subList(0,2);
subList.add("s1");
subList.remove(1);
System.out.println("list = " + list);
System.out.println("subList = " + subList);
複製代碼
輸出爲: list = [f1, s1, f3] subList = [f1, s1]優化
從輸出結果能夠看出,截取後的subList是能夠增刪查找的,而list是跟隨subList改變而改變的。緣由是,在初始化SubList的時候直接把ArrayList 自身傳了進去,在subList進行增刪查找時至關因而對ArrayList自身操做。ui
那在subList 執行增刪方法後還能夠操做list增刪嗎?答案:是能夠的,不過是有一個前提是 不能再對subList進行任何操做,包括輸出subList對象。 緊接上面的例子
subList.add("s2");
list.add("f4");
System.out.println("list = " + list);
list.remove("s1");
System.out.println("list = " + list);
複製代碼
輸出結果爲: list = [f1, s1, f3] subList = [f1, s1] list = [f1, s1, s2, f3, f4] list = [f1, s2, f3, f4]
若是對list進行操做後又對subList操做將會拋出ConcurrentModificationException
,緣由是ArrayList進行增刪時修改了modCount ,而 SubList的modCount並無被修改,檢測的時候兩者不相等因此拋出異常。
相關文章閱讀 Java集合系列之HashMap源碼分析
自定義View繪製過程源碼分析
ViewGroup繪製過程源碼分析
ThreadLocal 源碼分析
Handler消息機制源碼分析
Android 事件分發機制源碼分析
Activity啓動過程源碼分析
Activity中View建立到添加在Window窗口上到顯示的過程源碼分析