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倍后的大小,则按照此最小扩展数扩展,不然按照默认扩展。