Java編程中ArrayList源碼分析
之前看過一句話,說的特別好。有人問閱讀源碼有什么用?學習別人實現(xiàn)某個功能的設計思路,提高自己的編程水平。
是的,大家都實現(xiàn)一個功能,不同的人有不同的設計思路,有的人用一萬行代碼,有的人用五千行。有的人代碼運行需要的幾十秒,有的人只需要的幾秒。。下面進入正題了。
本文的主要內容:
· 詳細注釋了ArrayList的實現(xiàn),基于JDK 1.8 。
·迭代器SubList部分未詳細解釋,會放到其他源碼解讀里面。此處重點關注ArrayList本身實現(xiàn)。
·沒有采用標準的注釋,并適當調整了代碼的縮進以方便介紹
import java.util.AbstractList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.RandomAccess;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
/**
* 概述:
* List接口可調整大小的數(shù)組實現(xiàn)。實現(xiàn)所有可選的List操作,并允許所有元素,包括null,元素可重復。
* 除了列表接口外,該類提供了一種方法來操作該數(shù)組的大小來存儲該列表中的數(shù)組的大小。
*
* 時間復雜度:
* 方法size、isEmpty、get、set、iterator和listIterator的調用是常數(shù)時間的。
* 添加刪除的時間復雜度為O(N)。其他所有操作也都是線性時間復雜度。
*
* 容量:
* 每個ArrayList都有容量,容量大小至少為List元素的長度,默認初始化為10。
* 容量可以自動增長。
* 如果提前知道數(shù)組元素較多,可以在添加元素前通過調用ensureCapacity()方法提前增加容量以減小后期容量自動增長的開銷。
* 也可以通過帶初始容量的構造器初始化這個容量。
*
* 線程不安全:
* ArrayList不是線程安全的。
* 如果需要應用到多線程中,需要在外部做同步
*
* modCount:
* 定義在AbstractList中:protected transient int modCount = 0;
* 已從結構上修改此列表的次數(shù)。從結構上修改是指更改列表的大小,或者打亂列表,從而使正在進行的迭代產生錯誤的結果。
* 此字段由iterator和listiterator方法返回的迭代器和列表迭代器實現(xiàn)使用。
* 如果意外更改了此字段中的值,則迭代器(或列表迭代器)將拋出concurrentmodificationexception來響應next、remove、previous、set或add操作。
* 在迭代期間面臨并發(fā)修改時,它提供了快速失敗 行為,而不是非確定性行為。
* 子類是否使用此字段是可選的。
* 如果子類希望提供快速失敗迭代器(和列表迭代器),則它只需在其 add(int,e)和remove(int)方法(以及它所重寫的、導致列表結構上修改的任何其他方法)中增加此字段。
* 對add(int, e)或remove(int)的單個調用向此字段添加的數(shù)量不得超過 1,否則迭代器(和列表迭代器)將拋出虛假的 concurrentmodificationexceptions。
* 如果某個實現(xiàn)不希望提供快速失敗迭代器,則可以忽略此字段。
*
* transient:
* 默認情況下,對象的所有成員變量都將被持久化.在某些情況下,如果你想避免持久化對象的一些成員變量,你可以使用transient關鍵字來標記他們,transient也是java中的保留字(JDK 1.8)
*/
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
private static final long serialVersionUID = 8683452581122892189L;
//默認初始容量
private static final int DEFAULT_CAPACITY = 10;
//用于空實例共享空數(shù)組實例。
private static final Object[] EMPTY_ELEMENTDATA = {};
//默認的空數(shù)組
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
//對的,存放元素的數(shù)組,包訪問權限
transient Object[] elementData;
//大小,創(chuàng)建對象時Java會將int初始化為0
private int size;
//用指定的數(shù)設置初始化容量的構造函數(shù),負數(shù)會拋出異常
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);
}
}
//默認構造函數(shù),使用控數(shù)組初始化
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
//以集合的迭代器返回順序,構造一個含有集合中元素的列表
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toarray可能(錯誤地)不返回對象[](見JAVA BUG編號6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// 使用空數(shù)組
this.elementData = EMPTY_ELEMENTDATA;
}
}
//因為容量常常會大于實際元素的數(shù)量。內存緊張時,可以調用該方法刪除預留的位置,調整容量為元素實際數(shù)量。
//如果確定不會再有元素添加進來時也可以調用該方法來節(jié)約空間
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0) ? EMPTY_ELEMENTDATA : Arrays.copyOf(elementData, size);
}
}
//使用指定參數(shù)設置數(shù)組容量
public void ensureCapacity(int minCapacity) {
//如果數(shù)組為空,容量預取0,否則去默認值(10)
int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)? 0: DEFAULT_CAPACITY;
//若參數(shù)大于預設的容量,在使用該參數(shù)進一步設置數(shù)組容量
if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
}
//用于添加元素時,確保數(shù)組容量
private void ensureCapacityInternal(int minCapacity) {
//使用默認值和參數(shù)中較大者作為容量預設值
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
//如果參數(shù)大于數(shù)組容量,就增加數(shù)組容量
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
//數(shù)組的最大容量,可能會導致內存溢出(VM內存限制)
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
//增加容量,以確保它可以至少持有由參數(shù)指定的元素的數(shù)目
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
//預設容量增加一半
int newCapacity = oldCapacity + (oldCapacity >> 1);
//取與參數(shù)中的較大值
if (newCapacity - minCapacity < 0)//即newCapacity<minCapacity
newCapacity = minCapacity;
//若預設值大于默認的最大值檢查是否溢出
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);
}
//檢查是否溢出,若沒有溢出,返回最大整數(shù)值(java中的int為4字節(jié),所以最大為0x7fffffff)或默認最大值
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) //溢出
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;
}
//返回數(shù)組大小
public int size() {
return size;
}
//是否為空
public boolean isEmpty() {
return size == 0;
}
//是否包含一個數(shù) 返回bool
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
//返回一個值在數(shù)組首次出現(xiàn)的位置,會根據是否為null使用不同方式判斷。不存在就返回-1。時間復雜度為O(N)
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;
}
//返回一個值在數(shù)組最后一次出現(xiàn)的位置,不存在就返回-1。時間復雜度為O(N)
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;
}
//返回副本,元素本身沒有被復制,復制過程數(shù)組發(fā)生改變會拋出異常
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
//轉換為Object數(shù)組,使用Arrays.copyOf()方法
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
//返回一個數(shù)組,使用運行時確定類型,該數(shù)組包含在這個列表中的所有元素(從第一到最后一個元素)
//返回的數(shù)組容量由參數(shù)和本數(shù)組中較大值確定
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
if (a.length < size)
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
//返回指定位置的值,因為是數(shù)組,所以速度特別快
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
//返回指定位置的值,但是會檢查這個位置數(shù)否超出數(shù)組長度
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
//設置指定位置為一個新值,并返回之前的值,會檢查這個位置是否超出數(shù)組長度
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
//添加一個值,首先會確保容量
public boolean add(E e) {
ensureCapacityInternal(size + 1);
elementData[size++] = e;
return true;
}
//指定位置添加一個值,會檢查添加的位置和容量
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1);
//public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
//src:源數(shù)組; srcPos:源數(shù)組要復制的起始位置; dest:目的數(shù)組; destPos:目的數(shù)組放置的起始位置; length:復制的長度
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);
elementData[--size] = null; //便于垃圾回收期回收
return oldValue;
}
//刪除指定元素首次出現(xiàn)的位置
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;
}
//快速刪除指定位置的值,之所以叫快速,應該是不需要檢查和返回值,因為只內部使用
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
}
//清空數(shù)組,把每一個值設為null,方便垃圾回收(不同于reset,數(shù)組默認大小有改變的話不會重置)
public void clear() {
modCount++;
for (int i = 0; i < size; i++) elementData[i] = null;
size = 0;
}
//添加一個集合的元素到末端,若要添加的集合為空返回false
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew);
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(); //要添加的數(shù)組
int numNew = a.length; //要添加的數(shù)組長度
ensureCapacityInternal(size + numNew); //確保容量
int numMoved = size - index;//不會移動的長度(前段部分)
if (numMoved > 0) //有不需要移動的,就通過自身復制,把數(shù)組后部分需要移動的移動到正確位置
System.arraycopy(elementData, index, elementData, index + numNew,numMoved);
System.arraycopy(a, 0, elementData, index, numNew); //新的數(shù)組添加到改變后的原數(shù)組中間
size += numNew;
return numNew != 0;
}
//刪除指定范圍元素。參數(shù)為開始刪的位置和結束位置
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = size - toIndex; //后段保留的長度
System.arraycopy(elementData, toIndex, elementData, fromIndex,numMoved);
int newSize = size - (toIndex-fromIndex);
for (int i = newSize; i < size; i++) {
elementData[i] = null;
}
size = newSize;
}
//檢查數(shù)否超出數(shù)組長度 用于添加元素時
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
//檢查是否溢出
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
//拋出的異常的詳情
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
//刪除指定集合的元素
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);//檢查參數(shù)是否為null
return batchRemove(c, false);
}
//僅保留指定集合的元素
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
/**
* 源碼解讀 BY http://anxpp.com/
* @param complement true時從數(shù)組保留指定集合中元素的值,為false時從數(shù)組刪除指定集合中元素的值。
* @return 數(shù)組中重復的元素都會被刪除(而不是僅刪除一次或幾次),有任何刪除操作都會返回true
*/
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
//遍歷數(shù)組,并檢查這個集合是否包含對應的值,移動要保留的值到數(shù)組前面,w最后值為要保留的元素的數(shù)量
//簡單點:若保留,就將相同元素移動到前段;若刪除,就將不同元素移動到前段
for (; r < size; r++)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
}finally {//確保異常拋出前的部分可以完成期望的操作,而未被遍歷的部分會被接到后面
//r!=size表示可能出錯了:c.contains(elementData[r])拋出異常
if (r != size) {
System.arraycopy(elementData, r,elementData, w,size - r);
w += size - r;
}
//如果w==size:表示全部元素都保留了,所以也就沒有刪除操作發(fā)生,所以會返回false;反之,返回true,并更改數(shù)組
//而w!=size的時候,即使try塊拋出異常,也能正確處理異常拋出前的操作,因為w始終為要保留的前段部分的長度,數(shù)組也不會因此亂序
if (w != size) {
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;//改變的次數(shù)
size = w; //新的大小為保留的元素的個數(shù)
modified = true;
}
}
return modified;
}
//保存數(shù)組實例的狀態(tài)到一個流(即它序列化)。寫入過程數(shù)組被更改會拋出異常
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{
int expectedModCount = modCount;
s.defaultWriteObject(); //執(zhí)行默認的反序列化/序列化過程。將當前類的非靜態(tài)和非瞬態(tài)字段寫入此流
// 寫入大小
s.writeInt(size);
// 按順序寫入所有元素
for (int i=0; i<size; i++) {
s.writeObject(elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
//上面是寫,這個就是讀了。
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
elementData = EMPTY_ELEMENTDATA;
// 執(zhí)行默認的序列化/反序列化過程
s.defaultReadObject();
// 讀入數(shù)組長度
s.readInt();
if (size > 0) {
ensureCapacityInternal(size);
Object[] a = elementData;
//讀入所有元素
for (int i=0; i<size; i++) {
a[i] = s.readObject();
}
}
}
//返回ListIterator,開始位置為指定參數(shù)
public ListIterator<E> listIterator(int index) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: "+index);
return new ListItr(index);
}
//返回ListIterator,開始位置為0
public ListIterator<E> listIterator() {
return new ListItr(0);
}
//返回普通迭代器
public Iterator<E> iterator() {
return new Itr();
}
//通用的迭代器實現(xiàn)
private class Itr implements Iterator<E> {
int cursor; //游標,下一個元素的索引,默認初始化為0
int lastRet = -1; //上次訪問的元素的位置
int expectedModCount = modCount;//迭代過程不運行修改數(shù)組,否則就拋出異常
//是否還有下一個
public boolean hasNext() {
return cursor != size;
}
//下一個元素
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();//檢查數(shù)組是否被修改
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();//檢查數(shù)組是否被修改
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
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++]);
}
cursor = i;
lastRet = i - 1;
checkForComodification();
}
//檢查數(shù)組是否被修改
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
//ListIterator迭代器實現(xiàn)
private class ListItr extends Itr implements ListIterator<E> {
ListItr(int index) {
super();
cursor = index;
}
public boolean hasPrevious() {
return cursor != 0;
}
public int nextIndex() {
return cursor;
}
public int previousIndex() {
return cursor - 1;
}
@SuppressWarnings("unchecked")
public E previous() {
checkForComodification();
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i;
return (E) elementData[lastRet = i];
}
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.set(lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void add(E e) {
checkForComodification();
try {
int i = cursor;
ArrayList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
//返回指定范圍的子數(shù)組
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, 0, fromIndex, toIndex);
}
//安全檢查
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 + ")");
}
//子數(shù)組
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;
}
public E set(int index, E e) {
rangeCheck(index);
checkForComodification();
E oldValue = ArrayList.this.elementData(offset + index);
ArrayList.this.elementData[offset + index] = e;
return oldValue;
}
public E get(int index) {
rangeCheck(index);
checkForComodification();
return ArrayList.this.elementData(offset + index);
}
public int size() {
checkForComodification();
return this.size;
}
public void add(int index, E e) {
rangeCheckForAdd(index);
checkForComodification();
parent.add(parentOffset + index, e);
this.modCount = parent.modCount;
this.size++;
}
public E remove(int index) {
rangeCheck(index);
checkForComodification();
E result = parent.remove(parentOffset + index);
this.modCount = parent.modCount;
this.size--;
return result;
}
protected void removeRange(int fromIndex, int toIndex) {
checkForComodification();
parent.removeRange(parentOffset + fromIndex,parentOffset + toIndex);
this.modCount = parent.modCount;
this.size -= toIndex - fromIndex;
}
public boolean addAll(Collection<? extends E> c) {
return addAll(this.size, c);
}
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index);
int cSize = c.size();
if (cSize==0)
return false;
checkForComodification();
parent.addAll(parentOffset + index, c);
this.modCount = parent.modCount;
this.size += cSize;
return true;
}
public Iterator<E> iterator() {
return listIterator();
}
public ListIterator<E> listIterator(final int index) {
checkForComodification();
rangeCheckForAdd(index);
final int offset = this.offset;
return new ListIterator<E>() {
int cursor = index;
int lastRet = -1;
int expectedModCount = ArrayList.this.modCount;
public boolean hasNext() {
return cursor != SubList.this.size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= SubList.this.size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (offset + i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[offset + (lastRet = i)];
}
public boolean hasPrevious() {
return cursor != 0;
}
@SuppressWarnings("unchecked")
public E previous() {
checkForComodification();
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (offset + i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i;
return (E) elementData[offset + (lastRet = i)];
}
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = SubList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (offset + i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[offset + (i++)]);
}
// update once at end of iteration to reduce heap write traffic
lastRet = cursor = i;
checkForComodification();
}
public int nextIndex() {
return cursor;
}
public int previousIndex() {
return cursor - 1;
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
SubList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = ArrayList.this.modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.set(offset + lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void add(E e) {
checkForComodification();
try {
int i = cursor;
SubList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = ArrayList.this.modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (expectedModCount != ArrayList.this.modCount)
throw new ConcurrentModificationException();
}
};
}
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, offset, fromIndex, toIndex);
}
private void rangeCheck(int index) {
if (index < 0 || index >= this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private void rangeCheckForAdd(int index) {
if (index < 0 || index > this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+this.size;
}
private void checkForComodification() {
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
}
public Spliterator<E> spliterator() {
checkForComodification();
return new ArrayListSpliterator<E>(ArrayList.this, offset,offset + this.size, this.modCount);
}
}
@Override
public void forEach(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int expectedModCount = modCount;
@SuppressWarnings("unchecked")
final E[] elementData = (E[]) this.elementData;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
action.accept(elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
/**
* Creates a <em><a href="Spliterator.html#binding" rel="external nofollow" >late-binding</a></em>
* and <em>fail-fast</em> {@link Spliterator} over the elements in this
* list.
*
* <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
* {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.
* Overriding implementations should document the reporting of additional
* characteristic values.
*
* @return a {@code Spliterator} over the elements in this list
* @since 1.8
*/
@Override
public Spliterator<E> spliterator() {
return new ArrayListSpliterator<>(this, 0, -1, 0);
}
/** Index-based split-by-two, lazily initialized Spliterator */
static final class ArrayListSpliterator<E> implements Spliterator<E> {
/*
* If ArrayLists were immutable, or structurally immutable (no
* adds, removes, etc), we could implement their spliterators
* with Arrays.spliterator. Instead we detect as much
* interference during traversal as practical without
* sacrificing much performance. We rely primarily on
* modCounts. These are not guaranteed to detect concurrency
* violations, and are sometimes overly conservative about
* within-thread interference, but detect enough problems to
* be worthwhile in practice. To carry this out, we (1) lazily
* initialize fence and expectedModCount until the latest
* point that we need to commit to the state we are checking
* against; thus improving precision. (This doesn't apply to
* SubLists, that create spliterators with current non-lazy
* values). (2) We perform only a single
* ConcurrentModificationException check at the end of forEach
* (the most performance-sensitive method). When using forEach
* (as opposed to iterators), we can normally only detect
* interference after actions, not before. Further
* CME-triggering checks apply to all other possible
* violations of assumptions for example null or too-small
* elementData array given its size(), that could only have
* occurred due to interference. This allows the inner loop
* of forEach to run without any further checks, and
* simplifies lambda-resolution. While this does entail a
* number of checks, note that in the common case of
* list.stream().forEach(a), no checks or other computation
* occur anywhere other than inside forEach itself. The other
* less-often-used methods cannot take advantage of most of
* these streamlinings.
*/
private final ArrayList<E> list;
private int index; // current index, modified on advance/split
private int fence; // -1 until used; then one past last index
private int expectedModCount; // initialized when fence set
/** Create new spliterator covering the given range */
ArrayListSpliterator(ArrayList<E> list, int origin, int fence,
int expectedModCount) {
this.list = list; // OK if null unless traversed
this.index = origin;
this.fence = fence;
this.expectedModCount = expectedModCount;
}
private int getFence() { // initialize fence to size on first use
int hi; // (a specialized variant appears in method forEach)
ArrayList<E> lst;
if ((hi = fence) < 0) {
if ((lst = list) == null)
hi = fence = 0;
else {
expectedModCount = lst.modCount;
hi = fence = lst.size;
}
}
return hi;
}
public ArrayListSpliterator<E> trySplit() {
int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
return (lo >= mid) ? null : // divide range in half unless too small
new ArrayListSpliterator<E>(list, lo, index = mid,
expectedModCount);
}
public boolean tryAdvance(Consumer<? super E> action) {
if (action == null)
throw new NullPointerException();
int hi = getFence(), i = index;
if (i < hi) {
index = i + 1;
@SuppressWarnings("unchecked") E e = (E)list.elementData[i];
action.accept(e);
if (list.modCount != expectedModCount)
throw new ConcurrentModificationException();
return true;
}
return false;
}
public void forEachRemaining(Consumer<? super E> action) {
int i, hi, mc; // hoist accesses and checks from loop
ArrayList<E> lst; Object[] a;
if (action == null)
throw new NullPointerException();
if ((lst = list) != null && (a = lst.elementData) != null) {
if ((hi = fence) < 0) {
mc = lst.modCount;
hi = lst.size;
}
else
mc = expectedModCount;
if ((i = index) >= 0 && (index = hi) <= a.length) {
for (; i < hi; ++i) {
@SuppressWarnings("unchecked") E e = (E) a[i];
action.accept(e);
}
if (lst.modCount == mc)
return;
}
}
throw new ConcurrentModificationException();
}
public long estimateSize() {
return (long) (getFence() - index);
}
public int characteristics() {
return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
}
}
@Override
public boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
// figure out which elements are to be removed
// any exception thrown from the filter predicate at this stage
// will leave the collection unmodified
int removeCount = 0;
final BitSet removeSet = new BitSet(size);
final int expectedModCount = modCount;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
@SuppressWarnings("unchecked")
final E element = (E) elementData[i];
if (filter.test(element)) {
removeSet.set(i);
removeCount++;
}
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
// shift surviving elements left over the spaces left by removed elements
final boolean anyToRemove = removeCount > 0;
if (anyToRemove) {
final int newSize = size - removeCount;
for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
i = removeSet.nextClearBit(i);
elementData[j] = elementData[i];
}
for (int k=newSize; k < size; k++) {
elementData[k] = null; // Let gc do its work
}
this.size = newSize;
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
return anyToRemove;
}
@Override
@SuppressWarnings("unchecked")
public void replaceAll(UnaryOperator<E> operator) {
Objects.requireNonNull(operator);
final int expectedModCount = modCount;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
elementData[i] = operator.apply((E) elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
@Override
@SuppressWarnings("unchecked")
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++;
}
}
總結
以上就是本文關于Java編程中ArrayList源碼分析的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
相關文章
Java中Spring MVC接收表單數(shù)據的常用方法
Spring MVC是Spring框架中的一個模塊,用于開發(fā)基于MVC(Model-View-Controller)架構的Web應用程序,它提供了一種輕量級的、靈活的方式來構建Web應用,同時提供了豐富的功能和特性,本文給大家介紹了Spring MVC接收表單數(shù)據的方法,需要的朋友可以參考下2024-05-05
Spring?Boot多數(shù)據源事務@DSTransactional的使用詳解
本文主要介紹了Spring?Boot多數(shù)據源事務@DSTransactional的使用詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-06-06
Java swing框架實現(xiàn)的貪吃蛇游戲完整示例
這篇文章主要介紹了Java swing框架實現(xiàn)的貪吃蛇游戲,結合完整實例形式分析了java使用swing框架結合awt圖形繪制實現(xiàn)貪吃蛇游戲的具體步驟與相關實現(xiàn)技巧,需要的朋友可以參考下2017-12-12

