多看原始碼之ArrayList原始碼分析
阿新 • • 發佈:2019-01-31
初始容量為0,當第一個元素進來後,容量設定為10
private static final int DEFAULT_CAPACITY = 10;
private static final Object[] EMPTY_ELEMENTDATA = {};
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData; // non-private to simplify nested class access
ArrayList中 用來儲存陣列的物件陣列 這個物件是transient 的,即不可被序列化的。
由此可見,ArrayList底層實際是在維護一個物件陣列
//可以通過改建構函式來初始化容量。
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) {//引數的意思是:形參集合的引數必須是E(是ArrayList中指定的泛型)的子類,而且c是不可以執行add的。
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)//如果不是Object陣列型別,則需要複製(存在強轉)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;//當集合的長度為空時,使用本類常量空集合,因為外來記憶體地址的不可信
}
}
補充:<? extends E>:不可以add,可以get(但是必須使用E來接受元素);<? super E>:可以add(E和E的子類),也可以get(但是類的資訊會丟失,使用Object引用來接受。
//陣列工具類public class Arrays{......}
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;
}
//將集合的大小修剪為集合的長度。
/**
* Trims the capacity of this <tt>ArrayList</tt> instance to be the
* list's current size. An application can use this operation to minimize
* the storage of an <tt>ArrayList</tt> instance.
*/
public void trimToSize() {
modCount++;//這個是修改次數
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
//下面是擴充容量
private void grow(int minCapacity) {//當第一個元素進來後就會初始化容量為10,一直到8(8+4-10>0)會將容量擴充到12,9對應13,10對應15
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);//新的容量為舊的容量1.5倍(注意:有可能會變為負數)
if (newCapacity - minCapacity < 0)
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);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();//如果為負數的話則丟擲記憶體溢位異常
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
public static final int MAX_VALUE = 0x7fffffff;
//這個方法使用到了Object的equals()方法,也就是傳進來的物件一定要重寫了Object物件的equals方法,否則為地址比較。
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;
}
//Object的equals方法
public boolean equals(Object obj) {
return (this == obj);
}
//是否包含呼叫了indexOf
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
//克隆方法
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
//protected transient int modCount = 0;AbstractList中的成員變數
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
}
//轉化為陣列,底層用的是Arrays的方法
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
public E get(int index) {
rangeCheck(index);//判斷引數合法性:index>size?
return elementData(index);
}
//set方法會返回被覆蓋的值
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
//永遠都返回true的方法
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
//在指定位置新增一個元素
public void add(int index, E element) {
rangeCheckForAdd(index);//index>size||index<0
ensureCapacityInternal(size + 1); // Increments modCount!!
//引數分別是:源陣列,源陣列中開始拷貝的位置,目標陣列,目標陣列中開始放元素的位置,拷貝的長度
System.arraycopy(elementData, index, elementData, index + 1,
size - index);//也就是將插入位置後的所有元素後移一位。
elementData[index] = element;
size++;
}
//System類的方法(public final class System)
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
//移除,拷貝完成後最有一個元素和倒數第二個元素重複。
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
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
return oldValue;
}
//根據元素移除,之所有分情況,是因為o為null是不能呼叫equals()方法。
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);//呼叫了System.arraycopy
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
//清除
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
//將另一個集合加入本list中
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
//在指定位置加入一個集合
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index);
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount
int numMoved = size - index;
//先騰出位置
if (numMoved > 0)
System.arraycopy(elementData, index, elementData, index + numNew,
numMoved);
//再將騰出的位置放入a陣列。
System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}
//這個方法沒有進行引數的合法性判斷,可能會丟擲IndexOutOfBoundsException異常
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// clear to let GC do its work
int newSize = size - (toIndex-fromIndex);
for (int i = newSize; i < size; i++) {
elementData[i] = null;
}
size = newSize;
}
//批量移除
// * Removes from this list all of its elements that are contained in the
// * specified collection.只要出現在c中的就移除掉
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
//批量保留
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
//這裡用到了Object類的一個靜態方法,以後可以用這個來代替自己寫的空判斷了,逼格高一點
public static <T> T requireNonNull(T obj) {
if (obj == null)
throw new NullPointerException();
return obj;
}
//批量移除實現,有修改過就返回true
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < size; r++)//從左往右走,發現在c中包含有的就排隊留下(假設為true)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
//即使c.contains()丟擲了異常,也要對已經完成的remove工作做收尾處理。
if (r != size) {//沒有走完就發生異常,將異常後面的移到前面已經排好隊的
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
if (w != size) {//相等的話就相當於沒有動過,不需要清理
// clear to let GC do its work
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
後面的是迭代器的,有需要了解的可以自己看下,哈哈。
private static final int DEFAULT_CAPACITY = 10;
private static final Object[] EMPTY_ELEMENTDATA = {};
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData; // non-private to simplify nested class access
ArrayList中 用來儲存陣列的物件陣列 這個物件是transient 的,即不可被序列化的。
由此可見,ArrayList底層實際是在維護一個物件陣列
//可以通過改建構函式來初始化容量。
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) {//引數的意思是:形參集合的引數必須是E(是ArrayList中指定的泛型)的子類,而且c是不可以執行add的。
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)//如果不是Object陣列型別,則需要複製(存在強轉)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;//當集合的長度為空時,使用本類常量空集合,因為外來記憶體地址的不可信
}
}
補充:<? extends E>:不可以add,可以get(但是必須使用E來接受元素);<? super E>:可以add(E和E的子類),也可以get(但是類的資訊會丟失,使用Object引用來接受。
//陣列工具類public class Arrays{......}
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;
}
//將集合的大小修剪為集合的長度。
/**
* Trims the capacity of this <tt>ArrayList</tt> instance to be the
* list's current size. An application can use this operation to minimize
* the storage of an <tt>ArrayList</tt> instance.
*/
public void trimToSize() {
modCount++;//這個是修改次數
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
//下面是擴充容量
private void grow(int minCapacity) {//當第一個元素進來後就會初始化容量為10,一直到8(8+4-10>0)會將容量擴充到12,9對應13,10對應15
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);//新的容量為舊的容量1.5倍(注意:有可能會變為負數)
if (newCapacity - minCapacity < 0)
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);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();//如果為負數的話則丟擲記憶體溢位異常
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
public static final int MAX_VALUE = 0x7fffffff;
//這個方法使用到了Object的equals()方法,也就是傳進來的物件一定要重寫了Object物件的equals方法,否則為地址比較。
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;
}
//Object的equals方法
public boolean equals(Object obj) {
return (this == obj);
}
//是否包含呼叫了indexOf
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
//克隆方法
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
//protected transient int modCount = 0;AbstractList中的成員變數
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
}
//轉化為陣列,底層用的是Arrays的方法
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
public E get(int index) {
rangeCheck(index);//判斷引數合法性:index>size?
return elementData(index);
}
//set方法會返回被覆蓋的值
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
//永遠都返回true的方法
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
//在指定位置新增一個元素
public void add(int index, E element) {
rangeCheckForAdd(index);//index>size||index<0
ensureCapacityInternal(size + 1); // Increments modCount!!
//引數分別是:源陣列,源陣列中開始拷貝的位置,目標陣列,目標陣列中開始放元素的位置,拷貝的長度
System.arraycopy(elementData, index, elementData, index + 1,
size - index);//也就是將插入位置後的所有元素後移一位。
elementData[index] = element;
size++;
}
//System類的方法(public final class System)
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
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
return oldValue;
}
//根據元素移除,之所有分情況,是因為o為null是不能呼叫equals()方法。
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);//呼叫了System.arraycopy
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
//清除
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
//將另一個集合加入本list中
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
//在指定位置加入一個集合
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index);
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount
int numMoved = size - index;
//先騰出位置
if (numMoved > 0)
System.arraycopy(elementData, index, elementData, index + numNew,
numMoved);
//再將騰出的位置放入a陣列。
System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}
//這個方法沒有進行引數的合法性判斷,可能會丟擲IndexOutOfBoundsException異常
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// clear to let GC do its work
int newSize = size - (toIndex-fromIndex);
for (int i = newSize; i < size; i++) {
elementData[i] = null;
}
size = newSize;
}
//批量移除
// * Removes from this list all of its elements that are contained in the
// * specified collection.只要出現在c中的就移除掉
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
//批量保留
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
//這裡用到了Object類的一個靜態方法,以後可以用這個來代替自己寫的空判斷了,逼格高一點
public static <T> T requireNonNull(T obj) {
if (obj == null)
throw new NullPointerException();
return obj;
}
//批量移除實現,有修改過就返回true
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < size; r++)//從左往右走,發現在c中包含有的就排隊留下(假設為true)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
//即使c.contains()丟擲了異常,也要對已經完成的remove工作做收尾處理。
if (r != size) {//沒有走完就發生異常,將異常後面的移到前面已經排好隊的
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
if (w != size) {//相等的話就相當於沒有動過,不需要清理
// clear to let GC do its work
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
後面的是迭代器的,有需要了解的可以自己看下,哈哈。