ArrayList介紹
對(duì)于ArrayList,相信大家都很熟悉,天天都會(huì)接觸到它。JangGwa從源碼角度再和你一起熟悉一下,先簡(jiǎn)單介紹下ArrayList。
1.基于數(shù)組實(shí)現(xiàn),是一個(gè)動(dòng)態(tài)數(shù)組,其容量能自動(dòng)增長(zhǎng)。
2.ArrayList不是線程安全的,建議在單線程中使用,多線程可以選擇Vector或CopyOnWriteArrayList。
3.實(shí)現(xiàn)了RandomAccess接口,可以通過下標(biāo)序號(hào)進(jìn)行快速訪問。
4.實(shí)現(xiàn)了Cloneable接口,能被克隆。
5.實(shí)現(xiàn)了Serializable接口,支持序列化。
ArrayList源碼解析
ArrayList繼承了AbstractList并實(shí)現(xiàn)了List,RandomAccess, Cloneable, java.io.Serializable 接口,上面做了相應(yīng)的介紹就不再闡述了。關(guān)鍵我們看兩個(gè)重要的屬性elementData和size。
elementData:保存了添加到ArrayList中的元素。實(shí)際上,elementData是個(gè)動(dòng)態(tài)數(shù)組,我們能通過構(gòu)造函數(shù) ArrayList(int initialCapacity)來執(zhí)行它的初始容量為initialCapacity;如果通過不含參數(shù)的構(gòu)造函數(shù)ArrayList()來創(chuàng)建ArrayList,則elementData的容量默認(rèn)是10。
size: 動(dòng)態(tài)數(shù)組的實(shí)際大小。
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
private static final long serialVersionUID = 8683452581122892189L;
private transient Object[] elementData;
private int size;
// ArrayList帶容量大小的構(gòu)造函數(shù)。
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
// ArrayList無參構(gòu)造函數(shù)。默認(rèn)容量是10。
public ArrayList() {
this(10);
}
elementData數(shù)組的大小會(huì)根據(jù)ArrayList容量的增長(zhǎng)而動(dòng)態(tài)的增長(zhǎng),具體的增長(zhǎng)方式,下面的ensureCapacity()函數(shù)會(huì)告訴你答案。
// 若ArrayList的容量不足以容納當(dāng)前的全部元素,設(shè)置新的容量=“(原始容量x3)/2 + 1”
public void ensureCapacity(int minCapacity) {
modCount++;
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
Object oldData[] = elementData;
int newCapacity = (oldCapacity * 3)/2 + 1;
if (newCapacity < minCapacity)
newCapacity = minCapacity;
elementData = Arrays.copyOf(elementData, newCapacity);
}
}
定位
// 獲取index位置的元素值
public E get(int index) {
RangeCheck(index);
return (E) elementData[index];
}
private void RangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: "+size);
}
添加
// 添加元素e
public boolean add(E e) {
// 確定ArrayList的容量大小
ensureCapacity(size + 1); // Increments modCount!!
// 添加e到ArrayList中
elementData[size++] = e;
return true;
}
// 將e添加到ArrayList的指定位置
public void add(int index, E element) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: "+size);
ensureCapacity(size+1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
// 將集合c追加到ArrayList中
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacity(size + numNew); // Increments modCount
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
// 從index位置開始,將集合c添加到ArrayList
public boolean addAll(int index, Collection<? extends E> c) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(
"Index: " + index + ", Size: " + size);
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacity(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;
}
刪除
// 刪除ArrayList指定位置的元素
public E remove(int index) {
RangeCheck(index);
modCount++;
E oldValue = (E) elementData[index];
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work
return oldValue;
}
// 刪除ArrayList的指定元素
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;
}
// 快速刪除第index個(gè)元素
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
// 從"index+1"開始,用后面的元素替換前面的元素。
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work
}
//刪除元素
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
// 便利ArrayList,找到“元素o”,則刪除,并返回true。
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
// 刪除fromIndex到toIndex之間的全部元素。
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved);
}
清空ArrayList
public void clear() {
modCount++;
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
克隆函數(shù)
public Object clone() {
try {
ArrayList<E> v = (ArrayList<E>) super.clone();
// 將當(dāng)前ArrayList的全部元素拷貝到v中
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();
}
}
總結(jié)
ArrayList 實(shí)際上是通過一個(gè)數(shù)組去保存數(shù)據(jù)的。當(dāng)我們使用無參構(gòu)造函數(shù)構(gòu)造ArrayList時(shí),則ArrayList的默認(rèn)容量大小是10。
當(dāng)ArrayList容量不足以容納全部元素時(shí),ArrayList會(huì)重新設(shè)置容量:新的容量=“(原始容量x3)/2 + 1”;如果設(shè)置后的新容量還不夠,則直接把新容量設(shè)置為傳入的參數(shù)。
ArrayList查找效率高,插入刪除元素的效率低。
ArrayList的克隆函數(shù),即是將全部元素克隆到一個(gè)數(shù)組中。
ArrayList實(shí)現(xiàn)java.io.Serializable的方式。當(dāng)寫入到輸出流時(shí),先寫入“容量”,再依次寫入“每一個(gè)元素”;當(dāng)讀出輸入流時(shí),先讀取“容量”,再依次讀取“每一個(gè)元素”。
toArray()會(huì)拋出“java.lang.ClassCastException”異常
原因:toArray()返回的是 Object[] 數(shù)組,Java不支持向下轉(zhuǎn)型。(例如,將Object[]轉(zhuǎn)換為的Integer[])
解決方案:
public static Integer[] vectorToArray2(ArrayList<Integer> v) {
Integer[] newText = (Integer[])v.toArray(new Integer[0]);
return newText;
}