list是java集合中很重要的一部分,而ArrayList是最經常使用的list,學習一下源碼仍是頗有必要的。(如下代碼來自jdk1.8.0_20)java
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
複製代碼
ArrayList繼承自AbstractList,實現了List,RandomAccess,Cloneable,java.io.Serializable接口,RandomAccess接口表示ArrayList能夠隨機訪問,由於ArrayList底層是數組實現的。數組
private static final int DEFAULT_CAPACITY = 10;
bash
private static final Object[] EMPTY_ELEMENTDATA = {};
dom
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
ide
transient Object[] elementData;
函數
ArrayList有3個構造函數,包括無參構造函數,參數爲int型的構造函數,參數爲集合的構造函數。學習
參數爲0時,elementData = EMPTY_ELEMENTDATA。第一次增長元素時擴容到1。ui
無參時,elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; 第一次增長元素時擴容爲默認容量10。this
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) {
// 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;
}
}
複製代碼
public boolean add(E e) {
ensureCapacityInternal(size + 1); // 添加元素時首先保證容量大小,而且modCount++
elementData[size++] = e; //容量大小足夠,對數組size位置賦值,size加1
return true;
}
複製代碼
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { //無參聲明時,最小容量爲默認大小10
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++; //修改次數加1
// 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); //新容量大小爲舊容量+舊容量/2
if (newCapacity - minCapacity < 0) //若是擴容1.5倍小於須要的最小容量,則使用最小容量,
例如new ArrayList(0)時,舊容量爲0,1.5倍仍爲0,而minCapacity爲1
newCapacity = minCapacity;
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); //使用Arrays類的copyOf方法複製數組
}
複製代碼
public E set(int index, E element) {
rangeCheck(index); //下標範圍檢查
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
複製代碼
public E get(int index) {
rangeCheck(index); //首先進行下標檢查
return elementData(index); //返回數組中的值
}
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
E elementData(int index) {
return (E) elementData[index];
}
複製代碼
remove方法spa
System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length),集合拷貝函數,五個參數分別表示:src源對象,srcPos源對象拷貝的起始下標,dest目標對象,destPos複製到目標對象的起始位置,length拷貝的長度
public E remove(int index) {
rangeCheck(index); //首先進行下標範圍檢查
modCount++; //修改次數加1
E oldValue = elementData(index);
int numMoved = size - index - 1; //計算須要移動的元素數量(刪除index上的數據以後,後面的數據須要前移1位)
if (numMoved > 0) //若是刪除的元素後有元素須要移動,調用System.arraycopy方法把後面的元素前移1位
System.arraycopy(elementData, index+1, elementData, index,
numMoved); //
elementData[--size] = null; // 最後一位賦值爲null,方便垃圾回收
return oldValue;
}
複製代碼
按元素刪除時,null分開判斷,由於null的equals結果老是返回false
public boolean remove(Object o) {
if (o == null) { //若是刪除的是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])) { //刪除非null的元素用equals判斷元素相等
fastRemove(index);
return true; //刪除第一個匹配的元素以後推出循環,再也不查找
}
}
return false;
}
//fastRemove(int index)方法和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 size() {
return size;
}
複製代碼
public boolean isEmpty() {
return size == 0;
}
複製代碼
public void clear() {
modCount++;
for (int i = 0; i < size; i++)
elementData[i] = null; //把數組中元素所有賦值爲null方便垃圾回收,釋放空間
size = 0;
}
複製代碼
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
複製代碼
public int lastIndexOf(Object o) {
if (o == null) {
for (int i = size-1; i >= 0; i--)
if (elementData[i]==null)
return i;
} else {
for (int i = size-1; i >= 0; i--)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
複製代碼
這就是咱們定義了ArrayList list=new ArrayList<>();而後獲取數組時使用String[] array= (String[]) list.toArray();會拋出Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;異常的緣由。
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
複製代碼
Arrays.copyOf(T[] original, int newLength)方法
public static <T> T[] copyOf(T[] original, int newLength) {
return (T[]) copyOf(original, newLength, original.getClass());
}
複製代碼
Arrays.copyOf(T[] original, int newLength, Class<? extends Object[]> newType)方法
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;
}
複製代碼
ArrayList還有一個toArray方法,須要傳入一個數組參數,從而避免上面這中類轉換異常。
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) a[size] = null; return a; } 複製代碼
public void sort(Comparator<? super E> c) {
final int expectedModCount = modCount;
Arrays.sort((E[]) elementData, 0, size, c);
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
複製代碼
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size); //下標範圍檢查
return new SubList(this, 0, fromIndex, toIndex); //返回一個SubList對象
}
static void subListRangeCheck(int fromIndex, int toIndex, int size) {
if (fromIndex < 0)
throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
if (toIndex > size)
throw new IndexOutOfBoundsException("toIndex = " + toIndex);
if (fromIndex > toIndex)
throw new IllegalArgumentException("fromIndex(" + fromIndex +
") > toIndex(" + toIndex + ")");
}
複製代碼
SubList是ArrayList的一個內部類,構造以下,能夠看出來SubList中並無存儲元素的數組,而是使用成員變量記錄父列表中下標,因此修改父列表中的元素,子列表中的元素也會變化。SubList也有add、set、get、size等方法,方法體和ArrayList中的方法基本同樣或者是調用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) {
this.parent = parent;
this.parentOffset = fromIndex;
this.offset = offset + fromIndex;
this.size = toIndex - fromIndex;
this.modCount = ArrayList.this.modCount;
}
add、set、get方法等。。。
}
複製代碼
Iterator是用於遍歷集合類的標準訪問方法,它能夠把訪問邏輯從不一樣類型的集合類中抽象出來,從而避免向客戶端暴露集合的內部結構。例如咱們使用for循環來遍歷list,對於ArrayList和LinkedList咱們就須要寫兩種不一樣的方法來訪問其中的元素,而且若是之後代碼中的ArrayList換成LinkedList也需求修改大量使用到的代碼。
咱們首先使用list的iterator()方法獲取該列表的Iterator對象,而後使用Iterator對象的hasNext方法來判斷是否還有元素,next方法返回一個元素,remove方法刪除返回的元素。
public Iterator<E> iterator() {
return new Itr();
}
private class Itr implements Iterator<E> {
int cursor; // 下一個返回元素的下標
int lastRet = -1; // 最後返回的元素的下標,若是是-1,表明沒有
int expectedModCount = modCount; //指望修改次數,用於fail-fast機制
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification(); //fail-fast機制檢查,若是有其餘線程修改了這個list,會拋出ConcurrentModificationException異常
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]; //返回元素,並記錄lastRet
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1; //remove方法執行事後,清除上次返回元素的記錄,不能再次調用該方法。
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();
}
}
複製代碼