記錄一下自己看的源碼剔桨,就當(dāng)復(fù)習(xí)了
引用
成員變量
//默認(rèn)容量
private static final int DEFAULT_CAPACITY = 10;
//空數(shù)組,用于無參構(gòu)造函數(shù)
private static final Object[] EMPTY_ELEMENTDATA = {};
//默認(rèn)空數(shù)組,用于有參構(gòu)造函數(shù)
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
//實(shí)際存儲(chǔ)元素的數(shù)組
transient Object[] elementData;
//集合元素?cái)?shù)量
private int size;
//集合最大容量
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
//父類變量娜谊,表示List容量修改次數(shù)
protected transient int modCount = 0;
構(gòu)造函數(shù)
1.無參構(gòu)造函數(shù)
public ArrayList() {
//無參構(gòu)造函數(shù)酒繁,elementData 指向DEFAULTCAPACITY_EMPTY_ELEMENTDATA 空數(shù)組
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
2.有參構(gòu)造函數(shù)
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
//初始化為一個(gè)容量為initialCapacity的數(shù)組
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
//elementData 指向EMPTY_ELEMENTDATA空數(shù)組
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
3.參數(shù)為集合的構(gòu)造函數(shù)
public ArrayList(Collection<? extends E> c) {
//參數(shù)集合轉(zhuǎn)為Array賦給存儲(chǔ)元素的數(shù)組
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[]
if (elementData.getClass() != Object[].class)
//元素為空時(shí)网严,復(fù)制數(shù)組,copyOf方法中有類型檢查
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// 若參數(shù)集合為空火的,則返回空數(shù)組EMPTY_ELEMENTDATA.
this.elementData = EMPTY_ELEMENTDATA;
}
}
添加
1.添加單個(gè)元素
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
//用無參構(gòu)造函數(shù),添加單個(gè)元素淑倾,大小為默認(rèn)容量10
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
//容量變化次數(shù)增加1
modCount++;
//判斷需要的實(shí)際元素容量是否大于數(shù)組容量馏鹤,是則擴(kuò)容
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
//容量增加為1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
//newCapacity 可能為0,此時(shí)采用傳入的minCapacity作為擴(kuò)容后的容量
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0)
throw new OutOfMemoryError();
//容量不能超過Integer.MAX_VALUE
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
擴(kuò)容機(jī)制如下:
1娇哆、先默認(rèn)將列表大小newCapacity增加原來一半湃累,即如果原來是10,則新的大小為15碍讨;
2治力、如果新的大小newCapacity依舊不能滿足add進(jìn)來的元素總個(gè)數(shù)minCapacity,則將列表大小改為和minCapacity一樣大;即如果擴(kuò)大一半后newCapacity為15勃黍,但add進(jìn)來的總元素個(gè)數(shù)minCapacity為20宵统,則15明顯不能存儲(chǔ)20個(gè)元素,那么此時(shí)就將newCapacity大小擴(kuò)大到20覆获,剛剛好存儲(chǔ)20個(gè)元素马澈;
3、如果擴(kuò)容后的列表大小大于2147483639,也就是說大于Integer.MAX_VALUE - 8,此時(shí)就要做額外處理了弄息,因?yàn)閷?shí)際總元素大小有可能比Integer.MAX_VALUE還要大痊班,當(dāng)實(shí)際總元素大小minCapacity的值大于Integer.MAX_VALUE,即大于2147483647時(shí)疑枯,此時(shí)minCapacity的值將變?yōu)樨?fù)數(shù)辩块,因?yàn)閕nt是有符號(hào)的,當(dāng)超過最大值時(shí)就變?yōu)樨?fù)數(shù)
public static <T> T[] copyOf(T[] original, int newLength) {
return (T[]) copyOf(original, newLength, original.getClass());
}
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
@SuppressWarnings("unchecked")
// 在創(chuàng)建新數(shù)組對象之前會(huì)先對傳入的數(shù)據(jù)類型進(jìn)行判定
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;
}
//參數(shù)為原array荆永,原起始位置废亭,目標(biāo)array,目標(biāo)起始位置具钥,需要復(fù)制的數(shù)組長度
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
2.指定位置添加元素
public void add(int index, E element) {
//位置檢查
rangeCheckForAdd(index);
//擴(kuò)容
ensureCapacityInternal(size + 1); // Increments modCount!!
//復(fù)制數(shù)組豆村,將原index及其以后的元素復(fù)制到index+1
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
//index位置賦值為添加的元素
elementData[index] = element;
size++;
}
3.添加集合中的元素
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
//擴(kuò)容
ensureCapacityInternal(size + numNew); // Increments modCount
//將集合中的元素復(fù)制到擴(kuò)容后的數(shù)組后
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
4.指定位置添加集合中的元素
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;
//判斷是否在數(shù)組中間插入元素
if (numMoved > 0)
//將原index到index+numMoved-1的元素復(fù)制到index+numNew及以后
System.arraycopy(elementData, index, elementData, index + numNew,
numMoved);
//將集合元素復(fù)制到index到index+numNew-1
System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}
刪除
1.刪除指定位置元素
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
//將index+1及以后的元素復(fù)制到Index,相當(dāng)于全部往前挪一位
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
//最后一個(gè)元素設(shè)置為null
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
2.刪除元素
public boolean remove(Object o) {
//循環(huán)判斷骂删,找到元素的位置掌动,然后調(dià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;
}
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
}
3.刪除指定范圍的元素
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = size - toIndex;
//將toIndex之后的元素挪動(dòng)到fromIndex
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// clear to let GC do its work
int newSize = size - (toIndex-fromIndex);
//數(shù)組末尾元素全部置null
for (int i = newSize; i < size; i++) {
elementData[i] = null;
}
size = newSize;
}
4.刪除集合中的所有元素
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
5.保留集合中的元素四啰,刪除其他元素(取交集)
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, 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++)
//根據(jù)complete條件判斷是否刪除該元素
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
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;
}
獲取集合對象
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
E elementData(int index) {
return (E) elementData[index];
}
其他方法
1.指定位置設(shè)值
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
2.判斷元素是否存在
public boolean contains(Object o) {
return indexOf(o) >= 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;
}
序列化機(jī)制
1.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 behavioural compatibility with clone()
s.writeInt(size);
// 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();
}
}
從上面的代碼中我們可以看出ArrayList其實(shí)是有對elementData進(jìn)行序列化的,只不過這樣做的原因是因?yàn)閑lementData中可能會(huì)有很多的null元素粗恢,為了不把null元素也序列化出去柑晒,所以自定義了writeObject和readObject方法。
2.readObject
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
elementData = EMPTY_ELEMENTDATA;
// Read in size, and any hidden stuff
s.defaultReadObject();
// Read in capacity
s.readInt(); // ignored
if (size > 0) {
// be like clone(), allocate array based upon size not capacity
ensureCapacityInternal(size);
Object[] a = elementData;
// Read in all elements in the proper order.
for (int i=0; i<size; i++) {
a[i] = s.readObject();
}
}
}
迭代器
public Iterator<E> iterator() {
return new Itr();
}
新建了一個(gè)叫Itr的對象眷射,Itr類其實(shí)是ArrayList的一個(gè)內(nèi)部類
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
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;
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();
}
}