您好,登錄后才能下訂單哦!
這篇文章主要介紹Java編程中ArrayList怎么用,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
本文的主要內(nèi)容:
· 詳細(xì)注釋了ArrayList的實(shí)現(xiàn),基于JDK 1.8 。
·迭代器SubList部分未詳細(xì)解釋?zhuān)瑫?huì)放到其他源碼解讀里面。此處重點(diǎn)關(guān)注ArrayList本身實(shí)現(xiàn)。
·沒(méi)有采用標(biāo)準(zhǔn)的注釋?zhuān)⑦m當(dāng)調(diào)整了代碼的縮進(jì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接口可調(diào)整大小的數(shù)組實(shí)現(xiàn)。實(shí)現(xiàn)所有可選的List操作,并允許所有元素,包括null,元素可重復(fù)。 * 除了列表接口外,該類(lèi)提供了一種方法來(lái)操作該數(shù)組的大小來(lái)存儲(chǔ)該列表中的數(shù)組的大小。 * * 時(shí)間復(fù)雜度: * 方法size、isEmpty、get、set、iterator和listIterator的調(diào)用是常數(shù)時(shí)間的。 * 添加刪除的時(shí)間復(fù)雜度為O(N)。其他所有操作也都是線性時(shí)間復(fù)雜度。 * * 容量: * 每個(gè)ArrayList都有容量,容量大小至少為L(zhǎng)ist元素的長(zhǎng)度,默認(rèn)初始化為10。 * 容量可以自動(dòng)增長(zhǎng)。 * 如果提前知道數(shù)組元素較多,可以在添加元素前通過(guò)調(diào)用ensureCapacity()方法提前增加容量以減小后期容量自動(dòng)增長(zhǎng)的開(kāi)銷(xiāo)。 * 也可以通過(guò)帶初始容量的構(gòu)造器初始化這個(gè)容量。 * * 線程不安全: * ArrayList不是線程安全的。 * 如果需要應(yīng)用到多線程中,需要在外部做同步 * * modCount: * 定義在AbstractList中:protected transient int modCount = 0; * 已從結(jié)構(gòu)上修改此列表的次數(shù)。從結(jié)構(gòu)上修改是指更改列表的大小,或者打亂列表,從而使正在進(jìn)行的迭代產(chǎn)生錯(cuò)誤的結(jié)果。 * 此字段由iterator和listiterator方法返回的迭代器和列表迭代器實(shí)現(xiàn)使用。 * 如果意外更改了此字段中的值,則迭代器(或列表迭代器)將拋出concurrentmodificationexception來(lái)響應(yīng)next、remove、previous、set或add操作。 * 在迭代期間面臨并發(fā)修改時(shí),它提供了快速失敗 行為,而不是非確定性行為。 * 子類(lèi)是否使用此字段是可選的。 * 如果子類(lèi)希望提供快速失敗迭代器(和列表迭代器),則它只需在其 add(int,e)和remove(int)方法(以及它所重寫(xiě)的、導(dǎo)致列表結(jié)構(gòu)上修改的任何其他方法)中增加此字段。 * 對(duì)add(int, e)或remove(int)的單個(gè)調(diào)用向此字段添加的數(shù)量不得超過(guò) 1,否則迭代器(和列表迭代器)將拋出虛假的 concurrentmodificationexceptions。 * 如果某個(gè)實(shí)現(xiàn)不希望提供快速失敗迭代器,則可以忽略此字段。 * * transient: * 默認(rèn)情況下,對(duì)象的所有成員變量都將被持久化.在某些情況下,如果你想避免持久化對(duì)象的一些成員變量,你可以使用transient關(guān)鍵字來(lái)標(biāo)記他們,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; //默認(rèn)初始容量 private static final int DEFAULT_CAPACITY = 10; //用于空實(shí)例共享空數(shù)組實(shí)例。 private static final Object[] EMPTY_ELEMENTDATA = {}; //默認(rèn)的空數(shù)組 private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; //對(duì)的,存放元素的數(shù)組,包訪問(wèn)權(quán)限 transient Object[] elementData; //大小,創(chuàng)建對(duì)象時(shí)Java會(huì)將int初始化為0 private int size; //用指定的數(shù)設(shè)置初始化容量的構(gòu)造函數(shù),負(fù)數(shù)會(huì)拋出異常 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); } } //默認(rèn)構(gòu)造函數(shù),使用控?cái)?shù)組初始化 public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } //以集合的迭代器返回順序,構(gòu)造一個(gè)含有集合中元素的列表 public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); if ((size = elementData.length) != 0) { // c.toarray可能(錯(cuò)誤地)不返回對(duì)象[](見(jiàn)JAVA BUG編號(hào)6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } else { // 使用空數(shù)組 this.elementData = EMPTY_ELEMENTDATA; } } //因?yàn)槿萘砍3?huì)大于實(shí)際元素的數(shù)量。內(nèi)存緊張時(shí),可以調(diào)用該方法刪除預(yù)留的位置,調(diào)整容量為元素實(shí)際數(shù)量。 //如果確定不會(huì)再有元素添加進(jìn)來(lái)時(shí)也可以調(diào)用該方法來(lái)節(jié)約空間 public void trimToSize() { modCount++; if (size < elementData.length) { elementData = (size == 0) ? EMPTY_ELEMENTDATA : Arrays.copyOf(elementData, size); } } //使用指定參數(shù)設(shè)置數(shù)組容量 public void ensureCapacity(int minCapacity) { //如果數(shù)組為空,容量預(yù)取0,否則去默認(rèn)值(10) int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)? 0: DEFAULT_CAPACITY; //若參數(shù)大于預(yù)設(shè)的容量,在使用該參數(shù)進(jìn)一步設(shè)置數(shù)組容量 if (minCapacity > minExpand) { ensureExplicitCapacity(minCapacity); } } //用于添加元素時(shí),確保數(shù)組容量 private void ensureCapacityInternal(int minCapacity) { //使用默認(rèn)值和參數(shù)中較大者作為容量預(yù)設(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ù)組的最大容量,可能會(huì)導(dǎo)致內(nèi)存溢出(VM內(nèi)存限制) private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; //增加容量,以確保它可以至少持有由參數(shù)指定的元素的數(shù)目 private void grow(int minCapacity) { int oldCapacity = elementData.length; //預(yù)設(shè)容量增加一半 int newCapacity = oldCapacity + (oldCapacity >> 1); //取與參數(shù)中的較大值 if (newCapacity - minCapacity < 0)//即newCapacity<minCapacity newCapacity = minCapacity; //若預(yù)設(shè)值大于默認(rèn)的最大值檢查是否溢出 if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); elementData = Arrays.copyOf(elementData, newCapacity); } //檢查是否溢出,若沒(méi)有溢出,返回最大整數(shù)值(java中的int為4字節(jié),所以最大為0x7fffffff)或默認(rèn)最大值 private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) //溢出 throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } //返回?cái)?shù)組大小 public int size() { return size; } //是否為空 public boolean isEmpty() { return size == 0; } //是否包含一個(gè)數(shù) 返回bool public boolean contains(Object o) { return indexOf(o) >= 0; } //返回一個(gè)值在數(shù)組首次出現(xiàn)的位置,會(huì)根據(jù)是否為null使用不同方式判斷。不存在就返回-1。時(shí)間復(fù)雜度為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; } //返回一個(gè)值在數(shù)組最后一次出現(xiàn)的位置,不存在就返回-1。時(shí)間復(fù)雜度為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; } //返回副本,元素本身沒(méi)有被復(fù)制,復(fù)制過(guò)程數(shù)組發(fā)生改變會(huì)拋出異常 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); } } //轉(zhuǎn)換為Object數(shù)組,使用Arrays.copyOf()方法 public Object[] toArray() { return Arrays.copyOf(elementData, size); } //返回一個(gè)數(shù)組,使用運(yùn)行時(shí)確定類(lèi)型,該數(shù)組包含在這個(gè)列表中的所有元素(從第一到最后一個(gè)元素) //返回的數(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; } //返回指定位置的值,因?yàn)槭菙?shù)組,所以速度特別快 @SuppressWarnings("unchecked") E elementData(int index) { return (E) elementData[index]; } //返回指定位置的值,但是會(huì)檢查這個(gè)位置數(shù)否超出數(shù)組長(zhǎng)度 public E get(int index) { rangeCheck(index); return elementData(index); } //設(shè)置指定位置為一個(gè)新值,并返回之前的值,會(huì)檢查這個(gè)位置是否超出數(shù)組長(zhǎng)度 public E set(int index, E element) { rangeCheck(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; } //添加一個(gè)值,首先會(huì)確保容量 public boolean add(E e) { ensureCapacityInternal(size + 1); elementData[size++] = e; return true; } //指定位置添加一個(gè)值,會(huì)檢查添加的位置和容量 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ù)組要復(fù)制的起始位置; dest:目的數(shù)組; destPos:目的數(shù)組放置的起始位置; length:復(fù)制的長(zhǎng)度 System.arraycopy(elementData, index, elementData, index + 1,size - index); elementData[index] = element; size++; } //刪除指定位置的值,會(huì)檢查添加的位置,返回之前的值 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; } //快速刪除指定位置的值,之所以叫快速,應(yīng)該是不需要檢查和返回值,因?yàn)橹粌?nèi)部使用 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ù)組,把每一個(gè)值設(shè)為null,方便垃圾回收(不同于reset,數(shù)組默認(rèn)大小有改變的話(huà)不會(huì)重置) public void clear() { modCount++; for (int i = 0; i < size; i++) elementData[i] = null; size = 0; } //添加一個(gè)集合的元素到末端,若要添加的集合為空返回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; } //功能同上,從指定位置開(kāi)始添加 public boolean addAll(int index, Collection<? extends E> c) { rangeCheckForAdd(index); Object[] a = c.toArray(); //要添加的數(shù)組 int numNew = a.length; //要添加的數(shù)組長(zhǎng)度 ensureCapacityInternal(size + numNew); //確保容量 int numMoved = size - index;//不會(huì)移動(dòng)的長(zhǎng)度(前段部分) if (numMoved > 0) //有不需要移動(dòng)的,就通過(guò)自身復(fù)制,把數(shù)組后部分需要移動(dòng)的移動(dòng)到正確位置 System.arraycopy(elementData, index, elementData, index + numNew,numMoved); System.arraycopy(a, 0, elementData, index, numNew); //新的數(shù)組添加到改變后的原數(shù)組中間 size += numNew; return numNew != 0; } //刪除指定范圍元素。參數(shù)為開(kāi)始刪的位置和結(jié)束位置 protected void removeRange(int fromIndex, int toIndex) { modCount++; int numMoved = size - toIndex; //后段保留的長(zhǎng)度 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ù)組長(zhǎng)度 用于添加元素時(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í)從數(shù)組保留指定集合中元素的值,為false時(shí)從數(shù)組刪除指定集合中元素的值。 * @return 數(shù)組中重復(fù)的元素都會(huì)被刪除(而不是僅刪除一次或幾次),有任何刪除操作都會(huì)返回true */ private boolean batchRemove(Collection<?> c, boolean complement) { final Object[] elementData = this.elementData; int r = 0, w = 0; boolean modified = false; try { //遍歷數(shù)組,并檢查這個(gè)集合是否包含對(duì)應(yīng)的值,移動(dòng)要保留的值到數(shù)組前面,w最后值為要保留的元素的數(shù)量 //簡(jiǎn)單點(diǎn):若保留,就將相同元素移動(dòng)到前段;若刪除,就將不同元素移動(dòng)到前段 for (; r < size; r++) if (c.contains(elementData[r]) == complement) elementData[w++] = elementData[r]; }finally {//確保異常拋出前的部分可以完成期望的操作,而未被遍歷的部分會(huì)被接到后面 //r!=size表示可能出錯(cuò)了:c.contains(elementData[r])拋出異常 if (r != size) { System.arraycopy(elementData, r,elementData, w,size - r); w += size - r; } //如果w==size:表示全部元素都保留了,所以也就沒(méi)有刪除操作發(fā)生,所以會(huì)返回false;反之,返回true,并更改數(shù)組 //而w!=size的時(shí)候,即使try塊拋出異常,也能正確處理異常拋出前的操作,因?yàn)閣始終為要保留的前段部分的長(zhǎng)度,數(shù)組也不會(huì)因此亂序 if (w != size) { for (int i = w; i < size; i++) elementData[i] = null; modCount += size - w;//改變的次數(shù) size = w; //新的大小為保留的元素的個(gè)數(shù) modified = true; } } return modified; } //保存數(shù)組實(shí)例的狀態(tài)到一個(gè)流(即它序列化)。寫(xiě)入過(guò)程數(shù)組被更改會(huì)拋出異常 private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{ int expectedModCount = modCount; s.defaultWriteObject(); //執(zhí)行默認(rèn)的反序列化/序列化過(guò)程。將當(dāng)前類(lèi)的非靜態(tài)和非瞬態(tài)字段寫(xiě)入此流 // 寫(xiě)入大小 s.writeInt(size); // 按順序?qū)懭胨性? for (int i=0; i<size; i++) { s.writeObject(elementData[i]); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } //上面是寫(xiě),這個(gè)就是讀了。 private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { elementData = EMPTY_ELEMENTDATA; // 執(zhí)行默認(rèn)的序列化/反序列化過(guò)程 s.defaultReadObject(); // 讀入數(shù)組長(zhǎng)度 s.readInt(); if (size > 0) { ensureCapacityInternal(size); Object[] a = elementData; //讀入所有元素 for (int i=0; i<size; i++) { a[i] = s.readObject(); } } } //返回ListIterator,開(kāi)始位置為指定參數(shù) public ListIterator<E> listIterator(int index) { if (index < 0 || index > size) throw new IndexOutOfBoundsException("Index: "+index); return new ListItr(index); } //返回ListIterator,開(kāi)始位置為0 public ListIterator<E> listIterator() { return new ListItr(0); } //返回普通迭代器 public Iterator<E> iterator() { return new Itr(); } //通用的迭代器實(shí)現(xiàn) private class Itr implements Iterator<E> { int cursor; //游標(biāo),下一個(gè)元素的索引,默認(rèn)初始化為0 int lastRet = -1; //上次訪問(wèn)的元素的位置 int expectedModCount = modCount;//迭代過(guò)程不運(yùn)行修改數(shù)組,否則就拋出異常 //是否還有下一個(gè) public boolean hasNext() { return cursor != size; } //下一個(gè)元素 @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; //向后移動(dòng)游標(biāo) return (E) elementData[lastRet = i]; //設(shè)置訪問(wèn)的位置并返回這個(gè)值 } //刪除元素 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迭代器實(shí)現(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怎么用”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。