深入瞭解ArrayList。
環境:
- eclipse 2019-03 (4.11.0)
- jdk-12.0.1
eclipse中查看源碼的方法:按住Ctrl鍵,鼠標左鍵單擊代碼(更詳細請百度)。
容器:在Java中,“集合”有另外的用途,所以ArrayList、HashMap等皆稱爲容器類,其創建的一個對象就是一個容器。
博文中涉及到的源碼:
- 類聲明
- 字段
- 構造器
- size(),isEmpty(),contains(),indexof(),lastIndexOf(),toArray()
- 獲得元素get()
- 修改元素set()
- 添加元素add()
- 刪除元素remove()
- 去除所有空trimToSize()
- 擴容機制
- 清空所有元素clear()
- 追加一個數組addAll()
- 移除元素集合removeAll()
- 遍歷元素iterator()
- 自定義序列化readObject(),writeObject()
- 重寫equals()和hashCode()
簡介
ArrayList是一個基於數組結構的List,與數組的最大區別在於其可以實現動態擴容。
ArrayList源碼分析
1、類聲明
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable{...}
源碼分析:
ArrayList繼承了抽象類AbstractList的同時還實現了接口List。AbstractList類聲明:
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E>{...}
可以看到AbstractList也實現了List接口,和HashMap等一樣,這樣的做法原因公認度最高的有兩種:1)、添加List接口是爲了Class類的getInterfaces這個方法可以直接返回List接口。2)、這就是寫法上的錯誤,並沒有什麼深意,這是得票最高的答案,回答者稱曾問過此段代碼的設計者Josh Bloch。
ArrayList實現了接口RandomAccess。RandomAccess聲明:
public interface RandomAccess {}
查看源碼可以看到RandomAccess只是一個標識接口,實現該接口的作用是能支持快速隨機訪問,具體可以看看ArrayList集合實現RandomAccess接口有何作用?爲何LinkedList集合卻沒實現這接口?
實現Cloneable接口(標識接口),該接口不包含任何方法,實現它僅僅是爲了指示可以使用Object類中的clone()方法來進行克隆。
public interface Cloneable {}
實現Serializable接口(標識接口),表示該類可以進行序列化。該接口表示所有的非transient和非static字段都可以被序列化。如果要實現transient字段與static字段的序列化保存,必須聲明writeObject和readObject方法
public interface Serializable {}
2、字段
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;
源碼分析:
DEFAULT_CAPACITY:數組的默認大小。
EMPTY_ELEMENTDATA :空數組。
DEFAULTCAPACITY_EMPTY_ELEMENTDATA:空數組。在調用無參構造器創建ArrayList對象時使用。
elementData:數組,用於存儲元素。
size:int類型,用於記錄已存儲的元素數量。
除了以上的字段之外,ArrayList中還有兩個字段是必須要知道的:
protected transient int modCount = 0; private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;//2147483631
第一個modCount:該字段不是在ArrayList中聲明的,而是其父類AbstractList中的字段,用於記錄ArrayList結構性變化的次數(涉及到結構變化的操作如add(),remove()等)。由於此字段的存在,在遍歷刪除元素的時候有很多注意事項,更多可以看看ArrayList.remove()的正確用法(Java隨筆)
第二個MAX_ARRAY_SIZE :該字段、、、算是一個標準吧。一般情況下,數組的最大容量就是該值,但是如果要分配的數組容量大於了該值,就會使用Integer.MAX_VALUE作爲數組容量。兩者相差8。
3、構造器
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);
}
}
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// defend against c.toArray (incorrectly) not returning Object[]
// (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
源碼分析:ArrayList有三個構造器
ArrayList(int initialCapacity):該構造函數要求傳入一個int值,作爲數組的初始大小。
ArrayList():無參構造器,創建一個空數組。
ArrayList(Collection<? extends E> c):根據已有的Collection容器對象創建新的ArrayList對象。
4、size(),isEmpty(),contains(),indexof(),lastIndexOf(),toArray()
public int size() {
return size;//返回已有元素數量
}
public boolean isEmpty() {
return size == 0;//返回true或false,判斷容器是否沒有存儲數據
}
public boolean contains(Object o) {
return indexOf(o) >= 0;//返回true或false,判斷容器是否包含指定元素
}
public int indexOf(Object o) {
return indexOfRange(o, 0, size);//根據元素值獲得元素在容器數組中的位置索引,從前往後
}
/*根據元素值獲得元素在容器數組中的位置索引分兩步:
*1、指定元素爲null,應該使用“==”進行判斷
*2、指定元素不爲null,應使用“equals()”進行判斷
*/
int indexOfRange(Object o, int start, int end) {
Object[] es = elementData;
if (o == null) {
for (int i = start; i < end; i++) {
if (es[i] == null) {
return i;
}
}
} else {
for (int i = start; i < end; i++) {
if (o.equals(es[i])) {
return i;
}
}
}
return -1;
}
public int lastIndexOf(Object o) {//根據元素值獲得元素在容器數組中的位置索引,從後往前
return lastIndexOfRange(o, 0, size);
}
int lastIndexOfRange(Object o, int start, int end) {
Object[] es = elementData;
if (o == null) {
for (int i = end - 1; i >= start; i--) {
if (es[i] == null) {
return i;
}
}
} else {
for (int i = end - 1; i >= start; i--) {
if (o.equals(es[i])) {
return i;
}
}
}
return -1;
}
public Object clone() {//重寫Object類中的clone方法,淺克隆
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
}
public Object[] toArray() {//返回一個新數組,數組中包含容器中所用元素。
return Arrays.copyOf(elementData, size);
}
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {//將容器中的數據複製到指定數組中
if (a.length < size)//若指定數組太小,則使用指定數組的類型新建一個數組
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)//若指定數組太大,將size位置設置爲null
a[size] = null;
return a;
}
補充:ArrayList中很多地方都用到了Arrays.copyOf()或System.arraycopy()進行數組的複製,兩者具體的區別在
- Arrays.copyOf()返回一個新數組
- System.arraycopy()沒有返回值,是將數據複製到給定的數組中
Arrays.copyOf()和System.arraycopy()的源碼分析可以看看Arrays.copyOf()&System.arraycopy()
5、獲得元素get()
public E get(int index) {
Objects.checkIndex(index, size);//Object中的靜態方法,用於判斷index範圍
return elementData(index);
}
源碼分析:get(int index)根據位置索引獲得元素。
判斷index時,若(index<0||index>=size)則會拋出異常outOfBoundsCheckIndex。這裏限制index的上限爲size是非常有必要的,因爲所有元素的索引值都在size以內,而size是小於數組長度的,若沒有限制index的上限爲size,則獲取的值將是null值而不會報出任何異常。
elementData()返回數組elementData中索引index處的元素。該方法是用於獲取元素,在ArrayList源碼中所有獲取數組中的元素都是調用該方法,而不是直接操作數組。
@SuppressWarnings("unchecked") E elementData(int index) { return (E) elementData[index]; }
這裏有一個設計問題,爲什麼不將判斷索引大小的語句Objects.checkIndex(index, size);放於elementData()方法中,而是寫進了get()方法?(接下來的set(),remove()等方法中皆是如此)爲何要將該語句在每一個方法中都寫一遍,而不是直接寫在elementData()中。寫個模仿ArrayList獲取元素的程序來分析:
import java.util.Objects; public class Run { int[] datas={10,20}; int elementData(int index) { return datas[index]; } public int get(int index) { Objects.checkIndex(index, 2); return elementData(index); } //main public static void main(String[] args) { Run run=new Run(); System.out.println(run.get(-1)); } }
這是ArrayList中的寫法,將索引設置爲-1,運行該程序,報錯信息爲
將Objects.checkIndex(index, 2);放入elementData()中後再運行程序,報錯信息爲
對比一下兩個錯誤信息,不同之處在於修改後的程序報錯信息多了一句at com.reflect.test.Run.elementData(Run.java:11),指向錯誤來源爲該方法中,但是elementData()方法的權限聲明並不是public的,意味着我們並不希望客戶端知道elementData()這個方法的存在,而報錯信息卻表明了該方法,違背了封裝原則。所以應該將判斷index大小的語句放置在我們希望能被客戶端知道的方法中。
6、修改元素set()
public E set(int index, E element) {
Objects.checkIndex(index, size);//檢查index大小是否符合要求
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
源碼分析:set()方法修改數據,返回原數據
第一步依然是判斷指定位置索引index大小是否在0~size-1中,若(index<0||index>=size)則會拋出異常outOfBoundsCheckIndex。
接着獲取原數據,設置新數據,返回原數據,程序結束。
7、添加元素add()
private void add(E e, Object[] elementData, int s) {//重載方法,方法私有,供內部方法調用
if (s == elementData.length)
elementData = grow();//若元素個數s已經達到了數組的大小,調用grow()擴容
elementData[s] = e;
size = s + 1;
}
public boolean add(E e) {//追加元素
modCount++;//記錄結構改變次數
add(e, elementData, size);//調用重載方法
return true;
}
public void add(int index, E element) {//在指定位置添加元素
rangeCheckForAdd(index);//若(index > size || index < 0)則拋出IndexOutOfBoundsException(outOfBoundsMsg(index))異常。
modCount++;//記錄結構改變次數
final int s;
Object[] elementData;
if ((s = size) == (elementData = this.elementData).length)
elementData = grow();//若size已經達到了數組的大小,調用grow()擴容
System.arraycopy(elementData, index,
elementData, index + 1,
s - index);//從插入位置index開始,後面的元素異常往後移
elementData[index] = element;
size = s + 1;
}
源碼分析:ArrayList向客戶端代碼提供了兩個可訪問的添加元素方法。
add(E e):在數組最後一個元素後面添加元素。調用了重載方法add(E e, Object[] elementData, int s)。返回true。
add(int index, E element):在指定位置添加元素。使用了System.arraycopy()來實現數據的移動。
8、刪除元素remove()
public E remove(int index) {//根據索引刪除元素,刪除成功返回原數據
Objects.checkIndex(index, size);//檢查index是否符合要求
final Object[] es = elementData;
@SuppressWarnings("unchecked") E oldValue = (E) es[index];
fastRemove(es, index);//調用方法,實現快速移除
return oldValue;//返回原數據
}
public boolean remove(Object o) {//刪除指定元素,刪除成功返回true,失敗返回false
final Object[] es = elementData;
final int size = this.size;
int i = 0;
found: {
if (o == null) {
for (; i < size; i++)
if (es[i] == null)
break found;//跳出found域
} else {
for (; i < size; i++)
if (o.equals(es[i]))
break found;//跳出found域
}
return false;
}
fastRemove(es, i);//調用方法,實現快速移除
return true;
}
private void fastRemove(Object[] es, int i) {//快速刪除元素
modCount++;
final int newSize;
if ((newSize = size - 1) > i)
System.arraycopy(es, i + 1, es, i, newSize - i);
es[size = newSize] = null;//非常有必要的一步。置空最後一位,方便GC快速回收。
}
源碼分析:ArrayList提供了兩個可訪問的remove()方法
remove(int index):在指定位置移除元素。移除成功,返回被移除的元素值
remove(Object o):移除指定元素。移除成功返回true,失敗返回false
快速刪除元素是利用System.arraycopy()來實現的,本地方法比循環移動元素更快。
9、去除所有空trimToSize()
public void trimToSize() {//將數組大小重新定義爲size,使得數組中沒有null空值
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
補充:trimToSize()使用了Arrays.copyOf()來實現重新設置數組大小,得到的是一個新的數組對象。
10、擴容機制
public void ensureCapacity(int minCapacity) {//確定數組容量,
if (minCapacity > elementData.length
&& !(elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
&& minCapacity <= DEFAULT_CAPACITY)) {
modCount++;//結構將改變,記錄數加一
grow(minCapacity);//調用grow()方法
}
}
private Object[] grow(int minCapacity) {//返回擴容後的新數組,主要用於addAll()
return elementData = Arrays.copyOf(elementData,
newCapacity(minCapacity));
}
private Object[] grow() {//主要用於add()
return grow(size + 1);
}
private int newCapacity(int minCapacity) {//計算獲得新數組的容量
// overflow-conscious code
int oldCapacity = elementData.length;//原數組容量
int newCapacity = oldCapacity + (oldCapacity >> 1);//計算後的新容量,原來的3/2
if (newCapacity - minCapacity <= 0) {//若自定義的新容量更大
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
return Math.max(DEFAULT_CAPACITY, minCapacity);
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return minCapacity;//問題,問題,問題????
}
return (newCapacity - MAX_ARRAY_SIZE <= 0)//判斷新容量是否超過了MAX_ARRAY_SIZE
? newCapacity
: hugeCapacity(minCapacity);
}
private static int hugeCapacity(int minCapacity) {//最大容量判斷
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE)
? Integer.MAX_VALUE
: MAX_ARRAY_SIZE;//兩者相差8
}
源碼分析:ArrayList擴容機制實現步驟爲
- 計算擴容後的大小(多數時候是擴容爲原容量的3/2倍)。
- 判斷擴容後的大小是否滿足要求,做出相應處理。
- 使用Arrays.copyOf()進行擴容,返回新數組。
問題,在方法 newCapacity(int minCapacity)中
此處直接返回了minCapacity,而沒有與MAX_ARRAY_SIZE進行比較。由於minCapacity可能存在很大的情況,於是會出現的問題是最終的數組容量遠大於MAX_ARRAY_SIZE。在以前的版本中,ArrayList關於擴容的源碼在涉及到這一步時是這樣寫得
至於爲什麼現在的版本中不這樣寫了,俺也不知道,俺也莫法問。
11、清空所有元素clear()
public void clear() {//清空所有元素
modCount++;//記錄結構改變
final Object[] es = elementData;
for (int to = size, i = size = 0; i < to; i++)
es[i] = null;//循環清空所有元素
}
12、追加一個數組addAll()
public boolean addAll(Collection<? extends E> c) {//追加另一個數組
Object[] a = c.toArray();
modCount++;//記錄結構改變
int numNew = a.length;
if (numNew == 0)
return false;
Object[] elementData;
final int s;
if (numNew > (elementData = this.elementData).length - (s = size))
elementData = grow(s + numNew);//擴容
System.arraycopy(a, 0, elementData, s, numNew);
size = s + numNew;
return true;
}
public boolean addAll(int index, Collection<? extends E> c) {//在指定位置開始插入一個數組
rangeCheckForAdd(index);
Object[] a = c.toArray();
modCount++;
int numNew = a.length;
if (numNew == 0)
return false;
Object[] elementData;
final int s;
if (numNew > (elementData = this.elementData).length - (s = size))
elementData = grow(s + numNew);//擴容
int numMoved = s - index;
if (numMoved > 0)
System.arraycopy(elementData, index,
elementData, index + numNew,
numMoved);
System.arraycopy(a, 0, elementData, index, numNew);
size = s + numNew;
return true;
}
13、移除元素集合removeAll()
public boolean removeAll(Collection<?> c) {//移除集合c與當前集合的所有交集
return batchRemove(c, false, 0, size);
}
boolean batchRemove(Collection<?> c, boolean complement,
final int from, final int end) {
Objects.requireNonNull(c);
final Object[] es = elementData;
int r;
// Optimize for initial run of survivors
for (r = from;; r++) {
if (r == end)
return false;
if (c.contains(es[r]) != complement)
break;
}
int w = r++;
try {
for (Object e; r < end; r++)
if (c.contains(e = es[r]) == complement)
es[w++] = e;
} catch (Throwable ex) {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
System.arraycopy(es, r, es, w, end - r);
w += end - r;
throw ex;
} finally {
modCount += end - w;
shiftTailOverGap(es, w, end);//整理數據,clear to let GC do its work
}
return true;
}
源碼分析:removeAll()和一樣,都是通過batchRemove()來實現對Collection集合與當前容器操作的。
在batchRemove()中通過contains()找出Collection集合與當前集合的交集。contains()中用到了equest()來判斷數據是否相同。
在batchRemove()中通過shiftTailOverGap()來清除當前容器中與Collection集合的所有交集。
private void shiftTailOverGap(Object[] es, int lo, int hi) {//clear to let GC do its work System.arraycopy(es, hi, es, lo, size - hi); for (int to = size, i = (size -= hi - lo); i < to; i++) es[i] = null; }
14、遍歷元素iterator()
public Iterator<E> iterator() {//返回迭代器對象,封裝在容器內部的迭代器
return new Itr();
}
private class Itr implements Iterator<E> {//迭代器實現類,主要了解hasNext(),next()
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
// prevent creating a synthetic constructor
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;//ArrayList.this是ArrayList對象自身引用。這種用法在Java編程思想第193頁有提到。
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
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int size = ArrayList.this.size;
int i = cursor;
if (i < size) {
final Object[] es = elementData;
if (i >= es.length)
throw new ConcurrentModificationException();
for (; i < size && modCount == expectedModCount; i++)
action.accept(elementAt(es, i));
// update once at end to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
}
final void checkForComodification() {//檢查結構的改變次數
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
源碼分析:關於迭代的使用,最常用的方法是hasNext()和next()
hasNext():判斷是否還有下一個元素
next():獲取下一個元素
每次執行next()時,都會有一個關於modCount的檢查,若檢查的結果是false,則表示列表數據進行了結構性的變化,會拋出ConcurrentModificationException異常。
final void checkForComodification() {//檢查結構的改變次數 if (modCount != expectedModCount) throw new ConcurrentModificationException(); }
15、自定義序列化readObject(),writeObject()
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
// Write out element count, and any hidden stuff
int expectedModCount = modCount;
s.defaultWriteObject();//默認序列化
// Write out size as capacity for behavioral compatibility with clone()
s.writeInt(size);//write與read一一對應
// Write out all elements in the proper order.
for (int i=0; i<size; i++) {
s.writeObject(elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in size, and any hidden stuff
s.defaultReadObject();
// Read in capacity
s.readInt(); // ignored
if (size > 0) {
// like clone(), allocate array based upon size not capacity
SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Object[].class, size);
Object[] elements = new Object[size];
// Read in all elements in the proper order.
for (int i = 0; i < size; i++) {
elements[i] = s.readObject();
}
elementData = elements;
} else if (size == 0) {
elementData = EMPTY_ELEMENTDATA;
} else {
throw new java.io.InvalidObjectException("Invalid size: " + size);
}
}
源碼分析:writeObject(java.io.ObjectOutputStream s)方法和readObject(java.io.ObjectInputStream s)方法是實現序列化的兩個重要方法,聲明這兩個方法的目的是爲了實現自己可控制的序列化
序列化時,ObjectOutputStream會採用反射查找Serializable實現類內部是否聲明瞭這兩個方法,若有,則調用該方法。否則將採用默認的序列化進程。
16、重寫equals()和hashCode()
//equals()
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof List)) {
return false;
}
final int expectedModCount = modCount;
// ArrayList can be subclassed and given arbitrary behavior, but we can
// still deal with the common case where o is ArrayList precisely
boolean equal = (o.getClass() == ArrayList.class)
? equalsArrayList((ArrayList<?>) o)
: equalsRange((List<?>) o, 0, size);
checkForComodification(expectedModCount);
return equal;
}
boolean equalsRange(List<?> other, int from, int to) {
final Object[] es = elementData;
if (to > es.length) {
throw new ConcurrentModificationException();
}
var oit = other.iterator();
for (; from < to; from++) {
if (!oit.hasNext() || !Objects.equals(es[from], oit.next())) {
return false;
}
}
return !oit.hasNext();
}
private boolean equalsArrayList(ArrayList<?> other) {
final int otherModCount = other.modCount;
final int s = size;
boolean equal;
if (equal = (s == other.size)) {
final Object[] otherEs = other.elementData;
final Object[] es = elementData;
if (s > es.length || s > otherEs.length) {
throw new ConcurrentModificationException();
}
for (int i = 0; i < s; i++) {
if (!Objects.equals(es[i], otherEs[i])) {
equal = false;
break;
}
}
}
other.checkForComodification(otherModCount);
return equal;
}
private void checkForComodification(final int expectedModCount) {
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
//hashCode()
public int hashCode() {
int expectedModCount = modCount;
int hash = hashCodeRange(0, size);
checkForComodification(expectedModCount);
return hash;
}
int hashCodeRange(int from, int to) {
final Object[] es = elementData;
if (to > es.length) {
throw new ConcurrentModificationException();
}
int hashCode = 1;
for (int i = from; i < to; i++) {
Object e = es[i];
hashCode = 31 * hashCode + (e == null ? 0 : e.hashCode());
}
return hashCode;
}
源碼分析:
hashCode():基本上所有的hashCode都是一樣的算法,ArrayList中使用了容器中所有元素的hashCode()值來計算ArrayList對象的hashCode值。
值得注意的是,這兩個方法中都會檢測modCount值是否被改變。如果該值被改變,則表示容器發生結構性改變,會拋出ConcurrentModificationException異常。
總結
ArrayList的實質就是一個數組,只不過數組的大小不能隨意更改,而ArrayList可以。
- ArrayList擴容的代價是很大的,擴容機制的核心是創建一個大小適合的新數組對象,然後將原數組中的所有數據複製到新數組中,涉及到大量數據的轉移。
- 由於擴容代價大,因此在創建ArrayList對象的時候,如果能明確自己的需求,應該給定一個容器大小的初始值,避免擴容機制的不斷觸發。
雖然ArrayList的實質就是一個數組,但並不意味着我們應該在數組和ArrayList之間優先使用ArrayList。
- 當存儲的元素是基本類型時,應該綜合Java的運行時存儲機制進行考慮
- 列表存儲基本類型數據時,所有的數據都是存儲在棧中,訪問速度快且佔用內存小。
- 包括HashMap,ArrayList在內的所有的容器,都不能直接存儲基本類型數據,所有的基本數據類型都會被自動包裝成對應的包裝器類。
- 在用ArrayList存儲基本類型數據時,由於自動包裝機制,每一個基本類型數據都會被包裝爲一個對象,即所有的數據都會以對象的形式存儲在堆中。(當然不是所有的對象都存儲在堆中Java對象的創建及存儲位置)