ArrayList
是一个其容量可以动态增加
的动态数组java
继承关系图:segmentfault
咱们从源码角度看一下:数组
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable{ //默认容量大小 private static final int DEFAULT_CAPACITY = 10; //指定ArrayList容量为0时返回该数组 private static final Object[] EMPTY_ELEMENTDATA = {}; //当没有指定ArrayList容量时返回该数组 private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; //存放数据 transient Object[] elementData; //ArrayList中元素数量 private int size;
总结dom
10
elementData
数组存放数据注意:能够看到elementData被transient
标识,表明elementData没法被序列化,为何要这么设置呢?
由于elementData里面不是全部的元素都有数据,由于容量的问题,elementData里面有一些元素是空的,这种是没有必要序列化的。
ArrayList的序列化和反序列化依赖writeObject和readObject方法来实现。能够避免序列化空的元素。函数
//构造一个初始容量为10的空数组 public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } //构造一个具备初始容量值的空数组 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); } } //构造一个包含指定元素的数组 public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); if ((size = elementData.length) != 0) { // c.toArray 可能不会返回Object[](注释是这样说的),因此这里要判断一下类型 if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } else { //若是传入的c长度为0,则替换成空数组 this.elementData = EMPTY_ELEMENTDATA; } }
构造函数很简单,这里就很少说了!ui
/* * 添加元素到集合中 */ public boolean add(E e) { ensureCapacityInternal(size + 1);//判断ArrayList是否须要扩容 elementData[size++] = e; return true; } /*判断是否须要扩容——> minCapacity是集合须要的最小容量*/ private void ensureCapacityInternal(int minCapacity) { ensureExplicitCapacity(calculateCapacity(elementData, minCapacity)); } /*返回添加元素后的容量大小*/ private static int calculateCapacity(Object[] elementData, int minCapacity) { //首次添加元素时,返回 minCapacity > 10 ? minCapacity : 10 (首次可能使用addAll方法添加大量元素) if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { return Math.max(DEFAULT_CAPACITY, minCapacity); } return minCapacity; } /*判断是否须要扩容*/ private void ensureExplicitCapacity(int minCapacity) { modCount++;//modCount是继承自AbstractList的变量,用来表示集合被修改的次数 if (minCapacity - elementData.length > 0) grow(minCapacity); } /*扩容*/ private void grow(int minCapacity) { int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1);//扩容为原来的1.5倍 if (newCapacity - minCapacity < 0)//若是扩容后仍是小于最小容量,则设置minCapacity为容量大小 newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0)//MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8 newCapacity = hugeCapacity(minCapacity); //调用Arrays.copyOf生成新数组 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; }
到目前为止,咱们就能够知道add(E e)
的基本实现了:
添加元素时,首先去检查一下数组的容量是否足够,若是不够则扩容到原来的1.5
倍
扩容后,若是容量仍是小于minCapacity,就将容量扩充为minCapacitythis
那如何在指定位置添加元素呢?很简单,直接看源码吧spa
/* * 在指定位置添加元素 */ public void add(int index, E element) { rangeCheckForAdd(index);//参数校验 ensureCapacityInternal(size + 1); System.arraycopy(elementData, index, elementData, index + 1,size - index); elementData[index] = element; size++; } private void rangeCheckForAdd(int index) { if (index > size || index < 0) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); }
remove(int index)
:根据index计算须要左移的元素个数,调用System.arraycopy()
生成新数组/* * 删除index索引对象 */ 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; //设为null让JVM回收 return oldValue;//返回旧数据 }
remove(Object o)
:遍历数组后,删除给定元素/* * 删除给定Object对象 */ public boolean remove(Object o) { if (o == null) {//删除null对象-->ArrayList能够存放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++;//修改次数+1 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 }
removeAll(Collection<?> c)
:把须要移除的数据都替换掉,不须要移除的数据前移/* * 从elementData中移除包含在指定集合中的全部元素 */ public boolean removeAll(Collection<?> c) { Objects.requireNonNull(c);//判空——>if (c == null) throw new NullPointerException(); return batchRemove(c, false); } 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];//w为最后要保留的元素的数量 } finally { //当遍历过程当中抛出异常后,确保未遍历的元素能够接在后面(由于c.contains可能会抛出异常) if (r != size) { System.arraycopy(elementData, r,elementData, w,size - r); w += size - r; } if (w != size) { //GC回收(后面须要保留的元素已经被移到前面来了,因此直接把w后面的元素设为null) for (int i = w; i < size; i++) elementData[i] = null; modCount += size - w; size = w; modified = true; } } return modified; }
注意:调用remove删除元素时不会减小容量,若但愿减小容量则调用trimToSize()
code
/* * 获取index索引对象 */ public E get(int index) { rangeCheck(index);//参数校验 return elementData(index); } E elementData(int index) { return (E) elementData[index]; }
/* * 设置index索引对象 */ public E set(int index, E element) { rangeCheck(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; }
查找和更新逻辑很简单,这里就很少说了对象
接下来看看其它一些辅助函数
contains
判断集合中是否包含某元素
public boolean contains(Object o) { return indexOf(o) >= 0; }
indexOf
返回指定元素第一次出现的位置
/* * 返回指定元素第一次出现的位置(返回-1表示没有此元素) * lastIndexOf——>同理(其实就是从后向前遍历) */ 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; }
toArray
封装成数组后返回
/*返回Object数组*/ //Java不能对数组进行转型,Integer[] a = (Integer[]) objects会抛出ClassCastException异常,只能一个一个转 public Object[] toArray() { return Arrays.copyOf(elementData, size); } /*返回给定类型的数组*/ //Integer[] integers = list.toArray(new Integer[list.size()]); 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; }
iterator
public Iterator<E> iterator() { return new Itr(); }
Itr
是ArrayList的一个内部类
private class Itr implements Iterator<E> { int cursor; // 下次越过的元素索引 int lastRet = -1; // 上次越过的元素索引 int expectedModCount = modCount;//预期修改次数 Itr() {} /*判断是否有下一个元素*/ public boolean hasNext() { return cursor != size; } /*向后遍历并返回越过的元素*/ public E next() { checkForComodification();//fail-fast机制,不容许在遍历集合时修改元素 int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1;//调用next后cursor+1 return (E) elementData[lastRet = i];//为lastRet赋值——>i为调用next后越过的元素索引 } /*删除上次越过的元素(调用remove前要先调用next)*/ public void remove() { if (lastRet < 0) //lastRet 默认为-1 throw new IllegalStateException(); checkForComodification();//fail-fast try { ArrayList.this.remove(lastRet);//调用ArrayList.remove删除元素,这时modCount++ cursor = lastRet; //lastRet 从新设为-1,因此调用remove前要先调用next为lastRet赋值 lastRet = -1; //修改expectedModCount //所以当你须要在遍历时删除元素时,应该使用iterator.remove,而不是list.remove(iterator.next()); expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } /*操做未遍历的元素*/ public void forEachRemaining(Consumer<? super E> consumer) {//这里的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(); } //fail-fast final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
listIterator
public ListIterator<E> listIterator() { return new ListItr(0); }
ListItr
也是ArrayList的一个内部类,它继承了Itr
类,新添加了hasPrevious、nextIndex、previousIndex、previous等方法
private class ListItr extends Itr implements ListIterator<E> {//ListIterator<E> extends Iterator<E> //new ListItr(n)表明从n开始遍历 ListItr(int index) { super(); cursor = index; } /*判断是否有上一个元素*/ public boolean hasPrevious() { return cursor != 0; } /*返回下一次越过的元素索引*/ public int nextIndex() { return cursor; } /*返回上一次越过的元素索引*/ public int previousIndex() { return cursor - 1; } /*向前遍历*/ public E previous() { checkForComodification();//fail-fast int i = cursor - 1; if (i < 0) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i;//向前遍历-->cursor-1 return (E) elementData[lastRet = i];//为lastRet赋值并返回越过的元素 } /*设置元素*/ public void set(E e) { if (lastRet < 0)//这里也说明了调用set以前要先调用next或previous throw new IllegalStateException(); checkForComodification();//fail-fast try { ArrayList.this.set(lastRet, e);//调用ArrayList.set方法,这里没有修改modCount } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } /*添加元素*/ public void add(E e) { checkForComodification();//fail-fast try { int i = cursor; ArrayList.this.add(i, e);//调用ArrayList.add方法,modCount++ cursor = i + 1; lastRet = -1; expectedModCount = modCount;//从新设置expectedModCount } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } }
关于ArrayList源码咱们就看到这里,若有不当请多指教,对HashMap源码感兴趣的能够看下我另外一篇:深刻剖析HashMap源码