ArrayList简介
ArrayList是按照插入顺序来保存元素的(包含null),可以利用下标来查找值。它的优点是按照下标访问元素的速度非常快,它的缺点是元素插入和删除的速度非常慢,添加n个元素需要O(n)时间,ArrayList是非线程同步的。
源码解析
- 成员变量
/**
* Default initial capacity.
* 默认初始容量。
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* Shared empty array instance used for empty instances.
* 用于空实例的共享空数组实例。
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
*
*用于默认大小的空实例的共享空数组实例。 我们将此与EMPTY_ELEMENTDATA区分开来,以便在添加第一个元素时知道要扩充多少。
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
* 存储ArrayList元素的数组缓冲区。ArrayList的容量是此数组缓冲区的长度。 添加第一个元素时,任何带有elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA的空ArrayList都将扩展为DEFAULT_CAPACITY。
*/
transient Object[] elementData; // non-private to simplify nested class access
/**
* The size of the ArrayList (the number of elements it contains).
* ArrayList的大小(它包含的元素数)。
*
* @serial
*/
private int size;
/**
* The maximum size of array to allocate.
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
*
* 要分配的最大数组大小。 一些VM在阵列中保留一些标题字。
*尝试分配更大的数组可能会导致OutOfMemoryError:请求的数组大小超过VM限制
*
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
- 构造方法
/**
* Constructs an empty list with the specified initial capacity.
*
* 构造具有指定初始容量的空列表。
* @param initialCapacity the initial capacity of the list
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
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);
}
}
/**
* Constructs an empty list with an initial capacity of ten.
* 构造一个初始容量为10的空列表。
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* 按照集合的迭代器返回的顺序构造一个包含指定集合元素的列表。
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
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;
}
}
- 常用方法
- get(int index)方法。该方法的作用是返回此列表中指定位置的元素。
public E get(int index) { rangeCheck(index);//检查index是否合法,index不能>size return elementData(index); } E elementData(int index) { //elementData数据是ArrayList实际存放数据的地方 return (E) elementData[index]; }
- E set(int index)方法。该方法的作用是用指定的元素替换此列表中指定位置的元素。
public E set(int index, E element) { rangeCheck(index);//检测index是否合法,index不能>size E oldValue = elementData(index); elementData[index] = element; return oldValue; }
- boolean add(E e)方法。该方法的作用是将指定的元素追加到此列表的末尾。ArrayList列表容量扩充是在grow方法中,扩充的方式为原来数据长度的1.5倍
public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } private void ensureCapacityInternal(int minCapacity) { //判断列表是否为空,如果为空则将列表的默认容量设置为10 //如果列表为空的话,size = 0,那么minCapacity = size+1 = 1 if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); } private void ensureExplicitCapacity(int minCapacity) { modCount++;//操作次数+1 // overflow-conscious code //数据溢出意识 //如果minCapacity = size+1 大于elementData.length(数组本身的长度) if (minCapacity - elementData.length > 0) grow(minCapacity); } /* *增加容量以确保它至少可以容纳由minimum capacity参数指定的元素数。 * ArrayList列表容量扩充是在grow方法中,扩充的方式为原来数据长度的1.5倍 */ private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; //新的数据长度,扩充至原来的1.5倍 int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); }
- void add(int index, E element)方法。该方法的作用是在index坐标处插入一个元素,该index坐标后的元素整体往后移一个坐标点
public void add(int index, E element) { rangeCheckForAdd(index);//检测index是否合法,index不能大于size或小于0 // Increments modCount!! 设置列表的容量 ensureCapacityInternal(size + 1); /* * elementData 源数组 * index 在源数组中的起始位置 * elementData 目标数组 * index + 1 在目标数组中的起始位置 * size - index 要复制的数组元素的数量 */ System.arraycopy(elementData, index, elementData, index + 1,size - index); elementData[index] = element; size++; //列表的大小+1 }
- E remove(int index)方法。 该方法的作用是删除此列表中指定位置的元素。 将任何后续元素向左移位(从索引中减去一个)。
public E remove(int index) { rangeCheck(index);//index不能>=size modCount++; E oldValue = elementData(index); //numMoved得到的结果是数组中需要移动数据的数量 int numMoved = size - index - 1; //如果numMoved大于0,表示remove的元素在列表中间,如果numMoved等于0,表示remove的元素在列表末尾(不明白的可以自己画图) if (numMoved > 0) //将index后的元素整体左移一位 System.arraycopy(elementData, index+1, elementData, index, numMoved); //由于index后的元素整体左移一位或者只remove了最后一个元素,需要将最后一个元素设置为空 elementData[--size] = null; // clear to let GC do its work return oldValue; }
- boolean remove(Object o)。该方法是通过遍历的方式首先得到要删除元素的下标,然后再使用fastRemove(int index)方法来进行删除元素(fastRemove(int index)删除元素的方式和remove(int 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; } //fastRemove中删除数据的方式和remove(int index)方法中删除数据的方式一样 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 }
- void clear()。从此列表中删除所有元素。此调用返回后,列表将为空。
public void clear() { modCount++; // clear to let GC do its work //通过遍历的方式将每一个元素都设置为null for (int i = 0; i < size; i++) elementData[i] = null; size = 0; }
- boolean addAll(Collection<? extends E> c)。将指定集合中的所有元素按指定集合的迭代器返回的顺序附加到此列表的末尾。 如果在操作正在进行时修改了指定的集合,则此操作的行为是不确定的。 (这意味着如果指定的集合是此列表,则此调用的行为是未定义的,并且此列表是非空的。)
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; }
- boolean addAll(int index, Collection<? extends E> c)。从指定位置开始,将指定集合中的所有元素插入此列表。 将当前位置的元素(如果有)和任何后续元素向右移动(增加其索引)。 新元素将按照指定集合的迭代器返回的顺序出现在列表中。
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; }
- boolean removeAll(Collection<?> c)。从此列表中删除指定集合中包含的所有元素。
public boolean removeAll(Collection<?> c) { Objects.requireNonNull(c); 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]; } 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; } 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; }
- sort(Comparator<? super E> c)。将数组进行排序,Comparator是排序器,可自定义排序规则。
这里只给出了常用方法的分析。如有错误之处,请留言指出。@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++; }