一、目錄
-
源碼分析
- 構(gòu)造器
- 插入
- 刪除
- 迭代器(注意: foreach 做刪除操作拋出異常問題)
- 總結(jié)
- 示例代碼
- 參考資料
二洲愤、源碼分析
1. 構(gòu)造器
private static final Object[] EMPTY_ELEMENTDATA = {};
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
transient Object[] elementData;
// 參數(shù)表示初始化容量
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
// 空數(shù)組 {}
// private static final Object[] EMPTY_ELEMENTDATA = {};
this.elementData = EMPTY_ELEMENTDATA;
} else {
//容量 < 0 , 報異常
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
// 無參構(gòu)造器
public ArrayList() {
// 默認(rèn)創(chuàng)建一個空數(shù)組 {}
// private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
兩個構(gòu)造器都是初始化底層數(shù)組 elementData , 區(qū)別在于無參構(gòu)造方法會創(chuàng)建一個空數(shù)組, 插入元素時, 擴(kuò)容將會按默認(rèn)值重新初始化數(shù)組, 有參構(gòu)造方法則會根據(jù)參數(shù)創(chuàng)建一個長度 >=0 的數(shù)組.
2. 插入
private int size;
protected transient int modCount = 0;
private static final int DEFAULT_CAPACITY = 10;
public boolean add(E e) {
// 確定集合容量(是否擴(kuò)容)
ensureCapacityInternal(size + 1);
// 添加元素到集合的尾部, size +1
elementData[size++] = e;
return true;
}
public void add(int index, E element) {
// 檢查插入索引是否符合規(guī)范
rangeCheckForAdd(index);
// 確定集合容量(是否擴(kuò)容)
ensureCapacityInternal(size + 1);
// 將 index 及其之后的元素向后移動一位
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
// 替換掉 index 元素
elementData[index] = element;
size++;
}
public boolean addAll(Collection<? extends E> c) {
// 集合轉(zhuǎn)數(shù)組
Object[] a = c.toArray();
int numNew = a.length
// 確定集合容量(是否擴(kuò)容)
ensureCapacityInternal(size + numNew);
// 將數(shù)組元素添加到集合尾部
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
對于在數(shù)組尾部插入元素
- 檢查是否需要擴(kuò)容
- 將元素插入至數(shù)組尾部
對于根據(jù)索引插入元素
- 檢查是否需要擴(kuò)容
- 將 index 及其之后的元素向后移動一位
- 替換掉 index 元素
對于插入集合元素
- 將集合轉(zhuǎn)成數(shù)組
- 檢查是否需要擴(kuò)容
- 將數(shù)組元素添加到集合尾部
private void ensureCapacityInternal(int minCapacity) {
// 假如集合初始化時為空數(shù)組 {}
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
// 獲取最小容量
// private static final int DEFAULT_CAPACITY = 10;
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
// 確定集合容量(是否擴(kuò)容)
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// 假如集合容量大于初始化長度
if (minCapacity - elementData.length > 0)
// 擴(kuò)容
grow(minCapacity);
}
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
// 等價于 int newCapacity = oldCapacity + (oldCapacity * 0.5);
// 擴(kuò)容1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// 擴(kuò)容
elementData = Arrays.copyOf(elementData, newCapacity);
}
擴(kuò)容是按照之前容量的1.5倍進(jìn)行擴(kuò)充, 假如初始化數(shù)組為空, 則擴(kuò)容容量為10, 擴(kuò)容容量最大值為 Integer.MAX_VALUE
3. 刪除
public E remove(int index) {
// 檢查索引是否符合規(guī)范, index >= size 拋出異常
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
// 從索引開始到最后的數(shù)組長度
int numMoved = size - index - 1;
if (numMoved > 0)
// 將 index + 1 及之后的元素向前移動一位雹有,覆蓋被刪除值
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
// 最后一個元素設(shè)置為 null, size -1
elementData[--size] = null;
return oldValue;
}
public boolean remove(Object o) {
if (o == null) {
// 遍歷整個數(shù)組
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;
}
public void clear() {
modCount++;
// 遍歷, 清空所有元素
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
根據(jù)索引刪除元素
- 將 index + 1 及之后的元素向前移動一位阴挣,覆蓋被刪除值
- 最后一個元素設(shè)置為 null, size -1
- 返回被刪除的元素
根據(jù)對象刪除元素
- 遍歷整個數(shù)組
- 判斷數(shù)組是否含有該元素
- 刪除該元素
清空元素
- 遍歷, 將所有元素設(shè)置為null
注意:
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
往 ArrayList 插入大量元素, 然后又刪除了很多元素, 此時底層數(shù)組會空出大量的空間. 使用 trimToSize() 方法可以解決這個問題
4. 迭代器
private class Itr implements Iterator<E> {
// 下一個元素索引
int cursor;
// 上一個元素索引
int lastRet = -1;
int expectedModCount = modCount;
public boolean hasNext() {
// 如果cursor == size徘层,說明已經(jīng)遍歷完了呵俏,上一次遍歷的是最后一個元素
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
// 檢驗在遍歷過程中集合是否有做 add, remove 操作
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
// 下一個元素索引 = 元素索引 +1
cursor = i + 1;
// 返回迭代對象, 上一個元素索引 = 元素索引
return (E) elementData[lastRet = i];
}
public void remove() {
// 假如 lastRet < 0, 未獲取元素, 無法做刪除操作, 拋出異常
if (lastRet < 0)
throw new IllegalStateException();
// 檢驗在遍歷過程中集合是否有做 add, remove 操作
checkForComodification();
try {
// 根據(jù)索引做刪除操作
ArrayList.this.remove(lastRet);
// 下一個元素索引 = 元素索引
cursor = lastRet;
// 下一個元素索引 = -1
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
注意:
關(guān)于 foreach 遍歷做刪除操作時拋出異常的問題
ArrayList<Object> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
for (Object o : list) {
if (Objects.equals(2, o)) {
list.remove(o);
}
}
Java 中的 foreach 經(jīng)過編譯器編譯之后會被轉(zhuǎn)換成迭代器遍歷的方式, 等價于
ArrayList<Object> list = new ArrayList();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
Iterator var2 = list.iterator();
while(var2.hasNext()) {
Object o = var2.next();
if (Objects.equals(2, o)) {
list.remove(o);
}
}
根據(jù)上面的代碼可知, list 經(jīng)過 remove 操作 modCount 會進(jìn)行 +1 操作, 等到下一輪循環(huán)的 next() 方法中, checkForComodification() 方法用來判斷 list 是否有進(jìn)行 add / remove 操作, 此時 modCount +1, modCount != expectedModCount 為 true , 拋出 ConcurrentModificationException 異常
三铆惑、總結(jié)
- ArrayList 基于數(shù)組實現(xiàn), 可擴(kuò)容
- 添加元素時可能要擴(kuò)容, 刪除元素時不會自動減少容量, 可以使用 trimToSize() 方法進(jìn)行縮容處理**
- 線程不安全
- add(int index, E element) 添加元素到指定位置, 需要將索引及其以后的元素整塊向后移動一位(使用 System.arraycopy 方法)
- remove(Object o) 需要遍歷數(shù)組
- remove(int index) 不需要遍歷, 效率高于remove(Object o)
- contains(E) 亦需要遍歷數(shù)組
四范嘱、示例代碼
public static void main(String[] args) {
byte[] srcBytes = new byte[]{1,2,3,4,5,6}; // 源數(shù)組
System.arraycopy(srcBytes, 1, srcBytes, 3, 2);
System.out.println(Arrays.toString(srcBytes));
byte[] srcBytes2 = new byte[]{1,2,3,4,5,6};
byte[] desBytes = Arrays.copyOf(srcBytes2, 3);
System.out.println(Arrays.toString(desBytes));
ArrayList<Object> list = new ArrayList<>();
list.add("sss");
list.add("xxx");
list.add("zzz");
list.add("yyy");
list.add(1, "ooo");
list.remove(1);
list.remove("yyy");
list.set(1, "mmm");
list.get(1);
list.trimToSize();
System.out.println(list.toString());
Iterator<Object> iterator = list.iterator();
while (iterator.hasNext()) {
Object temp = iterator.next();
System.out.println(temp);
if (Objects.equals("zzz", temp)) {
iterator.remove();
}
}
System.out.println(list.toString());
ArrayList<Object> list2 = new ArrayList<>(2);
list2.add(1);
list2.add(2);
list.addAll(list2);
System.out.println("---");
for (Object o : list) {
if (Objects.equals("sss", o)) {
list.remove(o);
}
}
System.out.println(list.toString());
}
運(yùn)行結(jié)果:
[1, 2, 3, 2, 3, 6]
[1, 2, 3]
[sss, mmm, zzz]
sss
mmm
zzz
[sss, mmm]
---
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at Main.main(Main.java:145)