ArrayList的內部實現了動態數組,提供了動態的增長和減小元素,繼承AbstractList類,而且實現了List、RandomAccess、Cloneable和java.io.Serializable接口。ArrayList是一個數組隊列,提供添加、刪除、修改和遍歷元素的功能。由於實現RandomAccess接口,提供了隨機訪問的功能。現了Cloneable接口,即覆蓋了函數clone(),能被克隆。現java.io.Serializable接口,這意味着ArrayList支持序列化。ArrayList不是線程安全的,建議在單線程中訪問。
ArrayList有三個構造方法,定義以下:html
//建立給定初始化大小的ArrayList public ArrayList(int initialCapacity) {} //默認無參構造方法建立的ArrayList public ArrayList() {} //建立給定初始化集合c的ArrayList public ArrayList(Collection<? extends E> c) {}
ArrayList是經過動態數組實現的,下面經過源碼分析ArrayList的實現:java
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { /** * 默認初始化大小 */ private static final int DEFAULT_CAPACITY = 10; /** * 空數組實例 */ private static final Object[] EMPTY_ELEMENTDATA = {}; /** * 判斷是否爲第一次添加元素 */ private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; /** * ArrayList保存元素數據,經過elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA 來判斷是不是第一次添加元素 */ transient Object[] elementData; /** * ArrayList的實際大小 */ private int size; /** * 建立大小爲initialCapacity的空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); } } /** * 建立初始化容量爲10的list */ public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } /** * 經過集合c建立list * @param c the collection whose elements are to be placed into this list * @throws NullPointerException 若是c爲nulll,有空指針異常 */ public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); if ((size = elementData.length) != 0) { // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } else { // replace with empty array. this.elementData = EMPTY_ELEMENTDATA; } } /** * 縮小list容量爲當前真實大小 */ public void trimToSize() { modCount++; if (size < elementData.length) { elementData = (size == 0) ? EMPTY_ELEMENTDATA : Arrays.copyOf(elementData, size); } } //外部調用方法,調整容量,確保list不會越界 public void ensureCapacity(int minCapacity) { 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; if (minCapacity > minExpand) { ensureExplicitCapacity(minCapacity); } } //計算容量 private static int calculateCapacity(Object[] elementData, int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { return Math.max(DEFAULT_CAPACITY, minCapacity); } return minCapacity; } //內部調用方法,調整容量,確保list不會越界 private void ensureCapacityInternal(int minCapacity) { ensureExplicitCapacity(calculateCapacity(elementData, minCapacity)); } //擴展容量 private void ensureExplicitCapacity(int minCapacity) { modCount++; // 若是最小容量大於數組大小,進行數組擴展 if (minCapacity - elementData.length > 0) grow(minCapacity); } /** * 數組容量的最大值。部分虛擬機限制,大於MAX_ARRAY_SIZE,會致使OutOfMemoryError */ private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; /** * 數組按照1.5倍增長,若是增長後的值小於minCapacity,按照minCapacity增長 * */ private void grow(int minCapacity) { int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) 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(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } /** * 返回list實際大小 */ public int size() { return size; } /** * 若是實際大小爲0,返回true. */ public boolean isEmpty() { return size == 0; } /** * 返回元素是否存在,indexOf(o)方法返回-1表示不存在. */ public boolean contains(Object o) { return indexOf(o) >= 0; } /** * 返回元素的下標,-1表示元素不存在 */ 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; } /** * 返回最後一個元素o的下標 */ 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; } /** * copy一個list對象 */ 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); } } /** * 將list轉換爲對象 */ public Object[] toArray() { return Arrays.copyOf(elementData, size); } /** * 將list轉換爲對應類型的數組,若是數組大小小於size,經過Arrays.copyOf轉換,若是大於System.arraycopy轉換 */ public <T> T[] toArray(T[] a) { 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(elementData, 0, a, 0, size); if (a.length > size) a[size] = null; return a; } //經過制定下標返回一個元素 E elementData(int index) { return (E) elementData[index]; } /** * 根據下標獲取元素 * */ public E get(int index) { //檢查是否越界 rangeCheck(index); return elementData(index); } /** * 將指定位置的元素替換,返回老的元素 */ public E set(int index, E element) { rangeCheck(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; } /** * 在list中添加一個元素 */ public boolean add(E e) { //調整大小 ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } /** * 在指定位置添加一個元素 */ public void add(int index, E element) { rangeCheckForAdd(index); ensureCapacityInternal(size + 1); // Increments modCount!! //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; return oldValue; } /** * 根據指定的元素移除,調用fastRemove(index)方法 */ 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 } /** * 清除全部元素,size賦值0, */ public void clear() { modCount++; // clear to let GC do its work for (int i = 0; i < size; i++) elementData[i] = null; size = 0; } /** * 將集合c中的元素添加到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; } /** * 將集合c中的元素添加到index開始的位置,原index以後的元素後移 */ 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; } /** * 刪除指定區間的元素 */ 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; } /** * 檢查是否越界 */ 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; } /** * 刪除集合c中全部元素,首選檢查c是否爲空,調用batchRemove(c, false)方法 */ public boolean removeAll(Collection<?> c) { Objects.requireNonNull(c); return batchRemove(c, false); } /** * 保留給定集合的元素,刪除其餘的 * */ public boolean retainAll(Collection<?> c) { Objects.requireNonNull(c); return batchRemove(c, true); } /** * 根據complement判斷是刪除仍是保留給定的集合元素 * */ 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++) //將刪除或者保留的元素移動到數據前面 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; } //把w下標後的數據刪除 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; } /** * 將ArrayList保存到流中 */ 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對象 */ 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 int capacity = calculateCapacity(elementData, size); SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, 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(); } } } /** * 返回一個以index開始的ListIterator迭代器 */ public ListIterator<E> listIterator(int index) { if (index < 0 || index > size) throw new IndexOutOfBoundsException("Index: "+index); return new ListItr(index); } /** * 返回從0開始的ListIterator迭代器 */ public ListIterator<E> listIterator() { return new ListItr(0); } /** * 返回Iterator迭代器 */ public Iterator<E> iterator() { return new Itr(); } /** * 定義一個基於AbstractList.Itr優化後的迭代器內部類,後面詳細分析 */ private class Itr implements Iterator<E> {} /** * 定義一個基於 AbstractList.ListItr優化後的迭代器內部類,後面詳細分析 */ private class ListItr extends Itr implements ListIterator<E> {} /** *返回一個從fromIndex到toIndex的子list */ public List<E> subList(int fromIndex, int toIndex) { subListRangeCheck(fromIndex, toIndex, size); return new SubList(this, 0, fromIndex, toIndex); } //檢查獲取子list的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 + ")"); } //子list內部類 private class SubList extends AbstractList<E> implements RandomAccess {} @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">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> { } @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++; } }
上面分析了ArrayList源碼,其中Itr和ListItr這兩個內部類沒有詳細介紹。Itr和ListItr在AbstractList中有實現,在ArrayList對其進行了優化。下面進行詳細介紹:數組
Itr實現了Iterator接口,源碼以下:安全
private class Itr implements Iterator<E> { //下一個元素的下標 int cursor; // index of next element to return //最後返回元素的下標,若是不存在,返回-1 int lastRet = -1; /** * 每一個迭代器保存一個expectedModCount ,來記錄這個迭代器對對象進行結構性修改的次數。 * 每次迭代器進結構性修改的時候都將expectedModCount 和modCount進行對比 * 若是兩種相等則說明沒有其餘迭代器修改了對象,能夠進行。若是不相等則說明有迭代進行了修改,馬上拋出異常 */ int expectedModCount = modCount; Itr() {} //下一個元素下標不等於size,表示還有下一個元素 public boolean hasNext() { return cursor != size; } //獲取到下一個元素 public E next() { //檢查其餘迭代器對list是否有修改 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(); } } @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++]); } // update once at end of iteration to reduce heap write traffic cursor = i; lastRet = i - 1; checkForComodification(); } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
ListItr繼承自Itr,而且實現了ListIterator接口,源碼以下:多線程
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(); } } }
jdk 1.8之前的集合list遍歷支持三種方式,在1.8中增長了java 8 forEach方法,下面分別分析這四種遍歷方式以及效率:app
public class ArrayListIteratorTest { public static void main(String[] args) { List list = new ArrayList(); for (int i = 0; i < 1000000 ; i++) { list.add(i); } iteratorTest(list); foreashITest(list); foreashTest(list); java8ForeashTest(list); } /** * 經過迭代器遍歷 * @param list */ static void iteratorTest(List list){ long startTime; long endTime; startTime = System.currentTimeMillis(); Iterator iterator = list.iterator(); while (iterator.hasNext()){ iterator.next(); } endTime = System.currentTimeMillis(); System.out.println("Iterator time :" + (endTime - startTime)); } /** * 經過索引遍歷 * @param list */ static void foreashITest(List list){ long startTime; long endTime; startTime = System.currentTimeMillis(); for (int i = 0, length = list.size(); i < length; i++) { list.get(i); } endTime = System.currentTimeMillis(); System.out.println("fori time :" + (endTime - startTime)); } /** * 經過foreash遍歷 * @param list */ static void foreashTest(List list){ long startTime; long endTime; startTime = System.currentTimeMillis(); for (Object l: list) { } endTime = System.currentTimeMillis(); System.out.println("foreash time :" + (endTime - startTime)); } /** * 經過java 8 中提供的foreash遍歷 * @param list */ static void java8ForeashTest(List list){ long startTime; long endTime; startTime = System.currentTimeMillis(); list.forEach(l->{}); endTime = System.currentTimeMillis(); System.out.println("java 8 foreash time :" + (endTime - startTime)); } }
以上代碼運行後的結果以下:dom
從運行結果看,foreash運行效率最高,java 8 中的foreash運行效率最差。ide
ArrayList中提供了連個方法將list轉換爲數組,分別是Object[] toArray()和<T> T[] toArray(T[] a)。調用第一個方法會有拋出「java.lang.ClassCastException」異常的狀況,下面經過具體示例演示:函數
public class ArrayListToArraysTest { public static void main(String[] args) { List<Dog> list = new ArrayList<>(); Dog dog1 = new Dog(); Dog dog2 = new Dog(); list.add(dog1); list.add(dog2); //此處會拋出異常 Dog[] dogs1 = (Dog[]) list.toArray(); System.out.println(Arrays.toString(dogs1)); Dog[] dogs2 = new Dog[list.size()]; dogs2 = list.toArray(dogs2); System.out.println(Arrays.toString(dogs2)); } private static class Dog{ private String name; private String color; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } } }
當某一個線程A經過iterator去遍歷某集合的過程當中,若該集合的內容被其餘線程所改變了;那麼線程A訪問集合時,就會拋出ConcurrentModificationException異常,產生fail-fast事件。
Fail-fast示例以下:源碼分析
public class ArrayListFailFastTest { private static List list = new ArrayList(); public static void main(String[] args) { Thread t1 = new Thread(new ThreadTest(),"t1"); Thread t2 = new Thread(new ThreadTest(), "t2"); t1.start(); t2.start(); } private static class ThreadTest implements Runnable{ @Override public void run() { for (int i = 0; i < 20; i++) { list.add(i); } Iterator iterator = list.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next() + " "); } } } }
能夠看出,在多線程下,經過iterator去遍歷某集合,會拋ConcurrentModificationException異常。
在本章中,分析了ArrayList集合。ArrayList的內部是經過動態數組存儲數據的,默認初始大小是10,在jdk1.8中,默認構造方法建立對象,默認的數組爲空,當第一次添加元素時,設置數組大小爲10。在調整數組大小時,默認是增長原數組的1.5倍,若是傳入的最小擴展數大於增長1.5倍後的大小,則按照此最小擴展數擴展,不然按照默認擴展。