JDK 1.8 ArrayList源碼解讀
前言 System.arraycopy的使用
/**
* src被拷貝數組
* srcPos開始下標
* dest 被插入目標數組
* destPos被插入目標數組下標
* length 拷貝和複製的長度
*/
public static void arraycopy(Object src,
int srcPos,
Object dest,
int destPos,
int length);
/*
//eg:elementData[a,b]
a[0,1,2]
System.arraycopy(elementData, 0, a, 0, 2);
返回[a,b,2]
*/
全局變量
/**
* Shared empty array instance used for empty instances.
默認的空數組,用於構造函數或者重置ArrayList
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.
無參構造函數,帶默認容量10,時使用DEFAULTCAPACITY_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.
實際保存ArrrayList中元素的數組
ArrrayList當前容量(capacity)即此數組的長度
所有空的ArrayList都符合elementData ==DEFAULTCAPACITY_EMPTY_ELEMENTDATA
但當有元素插入,ArrayList將被擴充至DEFAULT_CAPACITY,即10
*/
transient Object[] elementData; // non-private to simplify nested class access
/**
* The size of the ArrayList (the number of elements it contains).
*當前ArrayList元素總數
* @serial
*/
private int size;
/**
* The maximum size of array to allocate.
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
構造函數
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {//明確默認長度的ArayList
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {//否則用EMPTY_ELEMENTDATAz作為存放元素的數組elementData
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
/**
* Constructs an empty list with an initial capacity of ten.
無參構造函數,帶默認容量10,時使用DEFAULTCAPACITY_EMPTY_ELEMENTDATA
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
Collection容器對象作參的構造函數
*/
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
//非Object[]數組即可進行數組複製(Object[]在數組複製時可能錯誤地不返回Object[] )
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
trimToSize瘦身
/*
ArrayList擴容是1.5+1的,此方法用於瘦身ArrayList,使用elementData的長度等於size
*/
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
ensureCapacity判斷(確保)ArrayLit容量大於minCapacity,否則擴容
public void ensureCapacity(int minCapacity) {
//DEFAULTCAPACITY_EMPTY_ELEMENTDATA表示ArrayList為默認容量10
int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
// any size if not default element table
? 0
// larger than default for default empty table. It's already
// supposed to be at default size.
: DEFAULT_CAPACITY;
//minExpand
if (minCapacity > minExpand) {//明確進行擴容
ensureExplicitCapacity(minCapacity);
}
}
minCapacity如果超過DEFAULT_CAPACITY(10)即進行擴容
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
ensureExplicitCapacity明確擴容
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
//大於當前數組容量即擴容
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
擴容實現grow
/**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
private void grow(int minCapacity) {
// overflow-conscious code
//oldCapacit原容量
int oldCapacity = elementData.length;
//擴容個1.5倍(其實不是1.5,隻是二進製右移1位 oldCapacity >> 1)
int newCapacity = oldCapacity + (oldCapacity >> 1);
//如果小於minCapacity(最小容量)則已minCapacity為準
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
//newCapacity比最大長度還大,則以Integer.MAX_VALUE作為容量
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);
}
hugeCapacity判斷最小容量
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
contains ArrayList是否包含此元素
public boolean contains(Object o) {
//該元素下標大於等於0即包含
return indexOf(o) >= 0;
}
迭代elementData判斷是否有此元素,有則直接返回下標
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;
}
反向迭代elementData判斷是否有此元素,有則直接返回下標
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;
}
重寫父類clone(),實現深度克隆
public 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);
}
}
arrayList轉成數組
//其實就是把elementData拷貝出來而已
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
//將ArrayList元素以T類型數組返回
public <T> T[] toArray(T[] a) {
//目標數組長度小於當前ArrayList size則直接拷貝elementData返回
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返回
//eg:elementData[a,b] a[0,1,2] 返回[a,b,2]
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
elementData[i]下標所在元素,沒做,判斷容易下標越界
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
返回下標元素
public E get(int index) {
rangeCheck(index);//檢查是否超出size
return elementData(index);
}
設置下標元素,並返回原值
public E set(int index, E element) {
rangeCheck(index); //檢查是否超出size
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
添加元素,先判斷是否需要擴容再添加
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
指定下標插入元素
public void add(int index, E element) {
rangeCheckForAdd(index);//檢查是否超出size
ensureCapacityInternal(size + 1); // Increments modCount!!擴容
//拷貝數組,elementDatazai在index處向前進一位
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
//插入元素
elementData[index] = element;
size++;
}
刪除指定下標數據
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);
//僅方便gc回收
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
移除指定元素
public boolean remove(Object o) {
//找出第一個空元素,執行刪除
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
//找出第一個obj,執行刪除
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
fastRemove 根據下標快速移除元素
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
//判斷目標下標是否在數組中間,是則執行拷貝
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,numMoved);
//yuan原數組尾元素置空
elementData[--size] = null; // clear to let GC do its work
}
### clear數組置空
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
### 添加另一個Collection對象所有元素進ArrayList
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;
}
指定下標添加Collection對象所有元素
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);
System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}
從指定區間元素開始刪除(不包含toIndex所在元素)
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;
}
移除包含在Collection中所有元素
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
批量刪除 complement true:刪除包含的,false:刪除不包含的
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
//迭代查找出符合complement的元素並依次保存elementData
for (; r < size; r++)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
//抽象地保存行為兼容性,即使c.contains()包含異常
//不等於意味迭代中間有異常
if (r != size) {
//將沒有判斷的元素拷貝至已經並且符合complement的元素前
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
//如果w == size,即全部符合complement無需移除
if (w != size) {
// clear to let GC do its work
//否則執行刪除下標W以後的元素
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
### 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();
}
}
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();
}
}
}
jdk7相關網頁
https://www.cnblogs.com/chenssy/p/3498468.html
最後更新:2017-08-13 22:33:54