ArrayList 的构造器

ArrayList 无参构造器初始化时,默认大小是空数组,并不是大家常说的 10,10 是在第一次 add 的时候扩容的数组值。

  1. public class ArrayList<E> extends AbstractList<E>
  2. implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
  3. private static final long serialVersionUID = 8683452581122892189L;
  4. // 默认初始容量
  5. private static final int DEFAULT_CAPACITY = 10;
  6. /**
  7. * Shared empty array instance used for empty instances.
  8. */
  9. // 用于空实例的共享空数组实例
  10. private static final Object[] EMPTY_ELEMENTDATA = {};
  11. private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
  12. // 数组缓冲区,数组列表的元素被存储在其中
  13. // 空数组列表时 elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
  14. // 将在添加第一个元素时扩展为 DEFAULT_CAPACITY
  15. // 非私有的,以简化嵌套类访问
  16. transient Object[] elementData;
  17. /**
  18. * The size of the ArrayList (the number of elements it contains).
  19. */
  20. // ArrayList 的大小(它包含的元素数量)
  21. // 没有使用 volatile 修饰,非线程安全的
  22. private int size;
  23. // 构造一个具有指定初始容量的空 ArrayList
  24. public ArrayList(int initialCapacity) {
  25. if (initialCapacity > 0) {
  26. this.elementData = new Object[initialCapacity];
  27. } else if (initialCapacity == 0) {
  28. this.elementData = EMPTY_ELEMENTDATA;
  29. } else {
  30. throw new IllegalArgumentException("Illegal Capacity: "+
  31. initialCapacity);
  32. }
  33. }
  34. // 构造一个初始容量为 10 的 ArrayList
  35. public ArrayList() {
  36. this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
  37. }
  38. // 构造一个包含指定元素的 ArrayList,集合 c 按照它的迭代器返回它们的顺序。
  39. public ArrayList(Collection<? extends E> c) {
  40. elementData = c.toArray();
  41. if ((size = elementData.length) != 0) {
  42. // c.toArray 可能(不正确)不返回对象[]
  43. if (elementData.getClass() != Object[].class)
  44. // 如果元素不是 Object[],将其转换成 Object[]
  45. elementData = Arrays.copyOf(elementData, size, Object[].class);
  46. } else {
  47. // 给定集合 c 无值,则替换为空数组
  48. this.elementData = EMPTY_ELEMENTDATA;
  49. }
  50. }
  51. // 统计当前数组结构修改的次数 (是 AbstractList 中的属性)
  52. protected transient int modCount = 0;

构造一个包含指定元素的 ArrayList 时,构造器中有一个这样的注释 see 6260652,这是 Java 的一个 bug,意思是:当给定集合内的元素不是 Object 类型时,我们会转化成 Object 的类型。
一般情况下都不会触发此 bug,只有在下列场景下才会触发:
ArrayList 初始化之后(ArrayList 元素非 Object 类型),再次调用 toArray 方法,得到 Object 数组,并且往 Object 数组赋值时,才会触发此 bug,问题在 Java 9 中被解决,代码和原因如图:

  1. @Test
  2. public void test17() {
  3. List<String> list = Arrays.asList("hello", "world");
  4. Object[] objArray = list.toArray();
  5. System.out.println(objArray.getClass().getSimpleName());
  6. // 打印结果为:String[]
  7. objArray[0] = new Object();
  8. // 抛出了 java.lang.ArrayStoreException: java.lang.Object
  9. }

ArrayList 的新增 & 扩容实现

新增就是往数组中添加元素,主要分成两步:

  • 判断是否需要扩容,如果需要执行扩容操作
  • 赋值操作

ArrayList 类中 add() 底层源码实现如下

  1. public boolean add(E e) {
  2. // 确保数组大小足够,不够执行扩容,size 为当前数组的大小
  3. ensureCapacityInternal(size + 1); // Increments modCount!!
  4. // 直接赋值,线程不安全
  5. elementData[size++] = e;
  6. return true;
  7. }
  8. public void add(int index, E element) {
  9. rangeCheckForAdd(index);
  10. ensureCapacityInternal(size + 1); // Increments modCount!!
  11. // 将索引位置为 i 的后面的元素后移一个位置
  12. System.arraycopy(elementData, index, elementData, index + 1,
  13. size - index);
  14. elementData[index] = element;
  15. size++;
  16. }
  17. // 如果传入的集合为 null,返回 false,否则返回 true
  18. public boolean addAll(int index, Collection<? extends E> c) {
  19. rangeCheckForAdd(index);
  20. Object[] a = c.toArray();
  21. int numNew = a.length;
  22. ensureCapacityInternal(size + numNew); // Increments modCount
  23. int numMoved = size - index;
  24. if (numMoved > 0)
  25. // 将索引位置为 i 的后面的元素后移 numNew 个位置
  26. System.arraycopy(elementData, index, elementData, index + numNew,
  27. numMoved);
  28. // 如果 index >= size,则在执行该方法时抛出 ArrayIndexOutOfBoundsException 异常
  29. System.arraycopy(a, 0, elementData, index, numNew);
  30. size += numNew;
  31. return numNew != 0;
  32. }

扩容的底层源码实现如下:

  1. private void ensureCapacityInternal(int minCapacity) {
  2. // 如果初始化数组大小时,有给定初始值,以给定的大小为准,不走 if 逻辑
  3. if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
  4. // 默认初始化大小第一次 add 时,执行此逻辑
  5. // minCapacity = 10;
  6. minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
  7. }
  8. // 确保容量达到 minCapacity(我们期望的最小容量)
  9. // 未达到则扩容
  10. ensureExplicitCapacity(minCapacity);
  11. }
  12. private void ensureExplicitCapacity(int minCapacity) {
  13. // 数组结构被修改次数 + 1
  14. modCount++;
  15. // 如果我们期望的最小容量 > 目前数组的长度,那么就扩容
  16. if (minCapacity - elementData.length > 0) {
  17. // 具体的扩容逻辑
  18. grow(minCapacity);
  19. }
  20. }
  21. // 要分配的数组的最大大小,有些虚拟机在数组中保留了一些 header words
  22. // 尝试分配更大的数组可能导致 OutOfMemoryError,请求的数组大小超过虚拟机限制
  23. private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
  24. // 扩容,并把现有数据拷贝到新的数组里面去
  25. // 如果按原数组大小的1.5倍扩容后 < 我们的期望值,则按照我们的期望值扩容
  26. // 如果按原数组大小的1.5倍扩容后 > 我们的期望值,则按照原数组大小的1.5倍扩容
  27. private void grow(int minCapacity) {
  28. int oldCapacity = elementData.length;
  29. int newCapacity = oldCapacity + (oldCapacity >> 1);
  30. // 如果扩容后的值 < 我们的期望值,扩容后的值就等于我们的期望值
  31. if (newCapacity - minCapacity < 0)
  32. newCapacity = minCapacity;
  33. if (newCapacity - MAX_ARRAY_SIZE > 0)
  34. // 如果扩容后的值 > jvm 所能分配的数组长度的最大值,执行此逻辑
  35. newCapacity = hugeCapacity(minCapacity);
  36. elementData = Arrays.copyOf(elementData, newCapacity);
  37. }
  38. private static int hugeCapacity(int minCapacity) {
  39. if (minCapacity < 0)
  40. throw new OutOfMemoryError();
  41. // 如果 期望容量 > (Integer.MAX_VALUE - 8),则扩容后的值将为 Integer.MAX_VALUE
  42. // 否则,扩容后的值将为 (Integer.MAX_VALUE - 8)
  43. return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;
  44. }

扩容的规则是:原来容量大小 + 原来容量大小的一半,直白来说,扩容后的大小是原来容量的 1.5 倍。
ArrayList 中的数组的最大值是 Integer.MAX_VALUE,超过这个值,JVM 就不会给数组分配内存空间了。
新增时,并没有对值进行严格的校验,所以 ArrayList 是允许 null 值的。
从新增和扩容源码中,下面这点值得我们借鉴:

  • 源码在扩容的时候,有数组大小溢出意识,就是说扩容后数组的大小下界不能小于 0,上界不能大于 Integer 的最大值,这种意识值得学习

扩容的本质
扩容是通过 Arrays.copyOf(elementData, newCapacity); 实现的,这行代码描述的本质是:数组之间的拷贝。
扩容是会先新建一个符合我们预期容量的新数组,然后把老数组的数据拷贝过去。
copyOf() 的底层代码实现如下:

  1. public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
  2. @SuppressWarnings("unchecked")
  3. T[] copy = ((Object)newType == (Object)Object[].class)
  4. ? (T[]) new Object[newLength]
  5. : (T[]) Array.newInstance(newType.getComponentType(), newLength);
  6. // 该方法是 native 的
  7. System.arraycopy(original, 0, copy, 0,
  8. Math.min(original.length, newLength));
  9. return copy;
  10. }
  11. /**
  12. * @param src 源数组
  13. * @param srcPos 源数组中的起始位置
  14. * @param dest 目标数组
  15. * @param destPos 目标数组中的起始位置
  16. * @param length 要拷贝的数组长度
  17. * 此方法是没有返回值的,通过 dest 的引用进行传值
  18. */
  19. public static native void arraycopy(Object src, int srcPos,
  20. Object dest, int destPos,
  21. int length);

ArrayList 的删除

ArrayList 删除元素有很多种方式,比如根据数组索引删除、根据值删除或批量删除等,原理和思路都差不多。
根据数组索引删除 底层源码实现如下:

  1. public E remove(int index) {
  2. // 该方法的唯一作用:如果 index >= size,抛出 IndexOutOfBoundsException
  3. rangeCheck(index);
  4. modCount++;
  5. E oldValue = elementData(index);
  6. // numMoved 表示删除 index 位置的元素后,需要从 index 后移动多少个元素到前面去
  7. int numMoved = size - index - 1;
  8. if (numMoved > 0)
  9. System.arraycopy(elementData, index+1, elementData, index,
  10. numMoved);
  11. // clear to let GC do its work
  12. // 让 GC 完成它的清理工作
  13. elementData[--size] = null;
  14. return oldValue;
  15. }

根据值删除 底层源码实现如下:

  1. // 找到第一个和要删除的值相等的删除
  2. public boolean remove(Object o) {
  3. if (o == null) {
  4. for (int index = 0; index < size; index++)
  5. if (elementData[index] == null) {
  6. fastRemove(index);
  7. return true;
  8. }
  9. } else {
  10. for (int index = 0; index < size; index++)
  11. // 根据 equals() 判断值是否相等,然后根据索引位置删除
  12. if (o.equals(elementData[index])) {
  13. fastRemove(index);
  14. return true;
  15. }
  16. }
  17. // size = 0 或未找到要删除的值时,返回 false
  18. return false;
  19. }
  20. private void fastRemove(int index) {
  21. modCount++;
  22. int numMoved = size - index - 1;
  23. if (numMoved > 0)
  24. System.arraycopy(elementData, index+1, elementData, index,
  25. numMoved);
  26. elementData[--size] = null;
  27. }

批量删除 底层源码实现如下:

  1. // 从 ArrayList 中删除指定集合中包含的所有元素
  2. public boolean removeAll(Collection<?> c) {
  3. // 保证集合 c 非空,为 null 时抛出 NullPointerException
  4. Objects.requireNonNull(c);
  5. return batchRemove(c, false);
  6. }
  7. // 从 ArrayList 中删除指定集合中不包含的所有元素
  8. public boolean retainAll(Collection<?> c) {
  9. Objects.requireNonNull(c);
  10. return batchRemove(c, true);
  11. }
  12. private boolean batchRemove(Collection<?> c, boolean complement) {
  13. final Object[] elementData = this.elementData;
  14. // r为遍历索引 w为结果索引。类似于双指针,r 是快指针,w 是慢指针
  15. int r = 0, w = 0;
  16. boolean modified = false;
  17. try {
  18. // 把需要移除的数据都替换掉,不需要移除的数据前移
  19. for (; r < size; r++)
  20. // if条件成立时,保存 elementData[r],不成立时不保存
  21. if (c.contains(elementData[r]) == complement)
  22. elementData[w++] = elementData[r];
  23. } finally {
  24. // Preserve behavioral compatibility with AbstractCollection,
  25. // even if c.contains() throws.
  26. // 存在并发修改
  27. if (r != size) {
  28. // 如果存在并发删除,则 size - r 为负数
  29. // 负数,System.arraycopy 会抛出 IndexOutOfBoundsException 运行时异常
  30. // 如果存在并发添加,则将添加的元素追加到 w 索引后面
  31. System.arraycopy(elementData, r, elementData, w, size - r);
  32. w += size - r;
  33. }
  34. // 成功删除了元素,将后面空间置空
  35. if (w != size) {
  36. // clear to let GC do its work
  37. // 让 GC 完成它的清理工作
  38. for (int i = w; i < size; i++)
  39. elementData[i] = null;
  40. modCount += size - w;
  41. size = w;
  42. modified = true;
  43. }
  44. }
  45. return modified;
  46. }

ArrayList 的修改

  1. public E set(int index, E element) {
  2. // 该方法的唯一作用:如果 index >= size,抛出 IndexOutOfBoundsException
  3. rangeCheck(index);
  4. E oldValue = elementData(index);
  5. elementData[index] = element;
  6. return oldValue;
  7. }

ArrayList 的查询

contains() 的源码实现如下:

  1. public boolean contains(Object o) {
  2. return indexOf(o) >= 0;
  3. }
  4. public int indexOf(Object o) {
  5. if (o == null) {
  6. for (int i = 0; i < size; i++)
  7. if (elementData[i]==null)
  8. return i;
  9. } else {
  10. for (int i = 0; i < size; i++)
  11. if (o.equals(elementData[i]))
  12. return i;
  13. }
  14. return -1;
  15. }
  16. public boolean containsAll(Collection<?> c) {
  17. for (Object e : c)
  18. if (!contains(e))
  19. return false;
  20. return true;
  21. }

get() 的源码实现如下:

  1. public E get(int index) {
  2. // 该方法的唯一作用:如果 index >= size,抛出 IndexOutOfBoundsException
  3. rangeCheck(index);
  4. return elementData(index);
  5. }
  6. E elementData(int index) {
  7. return (E) elementData[index];
  8. }

ArrayList 的迭代器

如果要自己实现迭代器,实现 java.util.Iterator 接口就好了,ArrayList 也是这样做的。
Iterator 和 ListIterator 接口的底层源码实现如下:

  1. public interface Iterator<E> {
  2. // 还有没有下一个值可以迭代,有返回 ture,无返回 false
  3. boolean hasNext();
  4. // 下一个可以迭代的值是多少
  5. E next();
  6. // 需要实现类重写实现该方法
  7. default void remove() {
  8. throw new UnsupportedOperationException("remove");
  9. }
  10. // Java8 新增的遍历操作方法
  11. default void forEachRemaining(Consumer<? super E> action) {
  12. Objects.requireNonNull(action);
  13. while (hasNext())
  14. action.accept(next());
  15. }
  16. }
  17. public interface ListIterator<E> extends Iterator<E> {
  18. boolean hasNext();
  19. E next();
  20. boolean hasPrevious();
  21. E previous();
  22. int nextIndex();
  23. int previousIndex();
  24. void remove();
  25. void set(E e);
  26. void add(E e);
  27. }

ArrayList 的 Iterator() 源码实现如下:

  1. public Iterator<E> iterator() {
  2. return new Itr();
  3. }
  4. // ListItr 继承该 Itr
  5. private class Itr implements Iterator<E> {
  6. // 下一次调用 next() 时返回的元素的索引
  7. int cursor;
  8. // 最近一次调用 next() 返回的元素的索引,若没有调用过,则默认 -1
  9. // 删除场景:如果索引位置 lastRet 上的元素被删除,则 lastRet 重置为 -1
  10. // 新增场景:如果通过 listIterator() 的 add() 在索引位置 lastRet 上新增,
  11. // 则索引位置 lastRet 后的元素后移一个位置,且 lastRet 重置为 -1
  12. int lastRet = -1;
  13. // expectedModCount:迭代过程中期望版本号;modCount:目前最新版本号
  14. int expectedModCount = modCount;
  15. // 空参构造器
  16. Itr() {}
  17. public boolean hasNext() {
  18. return cursor != size;
  19. }
  20. public E next() {
  21. // 迭代过程中,判断版本号有无被修改,有被修改,抛 ConcurrentModificationException
  22. checkForComodification();
  23. // 本次迭代过程中,元素的索引位置
  24. int i = cursor;
  25. if (i >= size)
  26. throw new NoSuchElementException();
  27. Object[] elementData = ArrayList.this.elementData;
  28. if (i >= elementData.length)
  29. throw new ConcurrentModificationException();
  30. // 下一次迭代时,元素的位置,为下一次迭代做准备
  31. cursor = i + 1;
  32. return (E) elementData[lastRet = i];
  33. }
  34. public void remove() {
  35. // lastRet < 0,存在不同的情况
  36. // 情况1:还没有迭代过,即还没有执行过 next()
  37. // 情况2:已经 remove() 一次,lastRest 被置为 -1,防止重复删除
  38. if (lastRet < 0)
  39. throw new IllegalStateException();
  40. // 迭代过程中,判断版本号有无被修改,有被修改,抛 ConcurrentModificationException 异常
  41. checkForComodification();
  42. try {
  43. ArrayList.this.remove(lastRet);
  44. // remove 后索引 lastRet 位置后的元素前移了,
  45. // 因此索引位置 lastRet 需要重新迭代
  46. cursor = lastRet;
  47. lastRet = -1;
  48. // 删除元素时 modCount 的值已经发生变化
  49. // 在此赋值给 expectedModCount 这样下次迭代时,两者的值是一致的
  50. expectedModCount = modCount;
  51. } catch (IndexOutOfBoundsException ex) {
  52. throw new ConcurrentModificationException();
  53. }
  54. }
  55. @Override
  56. @SuppressWarnings("unchecked")
  57. // Java8 新增的迭代操作方法
  58. public void forEachRemaining(Consumer<? super E> consumer) {
  59. Objects.requireNonNull(consumer);
  60. final int size = ArrayList.this.size;
  61. int i = cursor;
  62. if (i >= size) {
  63. return;
  64. }
  65. final Object[] elementData = ArrayList.this.elementData;
  66. if (i >= elementData.length) {
  67. throw new ConcurrentModificationException();
  68. }
  69. while (i != size && modCount == expectedModCount) {
  70. consumer.accept((E) elementData[i++]);
  71. }
  72. // update once at end of iteration to reduce heap write traffic
  73. cursor = i;
  74. lastRet = i - 1;
  75. checkForComodification();
  76. }
  77. final void checkForComodification() {
  78. if (modCount != expectedModCount)
  79. throw new ConcurrentModificationException();
  80. }
  81. }

ArrayList 的 listIterator() 源码实现如下:

  1. // 可以实现从中间 / 尾部迭代
  2. public ListIterator<E> listIterator(int index) {
  3. if (index < 0 || index > size)
  4. throw new IndexOutOfBoundsException("Index: "+index);
  5. return new ListItr(index);
  6. }
  7. // 双向迭代器
  8. private class ListItr extends Itr implements ListIterator<E> {
  9. // index 为迭代的起始索引位置
  10. ListItr(int index) {
  11. super();
  12. cursor = index;
  13. }
  14. // 该类继承 Itr,hasNext()、next() 在 Itr 类中有实现
  15. public boolean hasPrevious() {
  16. return cursor != 0;
  17. }
  18. public int nextIndex() {
  19. return cursor;
  20. }
  21. public int previousIndex() {
  22. return cursor - 1;
  23. }
  24. @SuppressWarnings("unchecked")
  25. public E previous() {
  26. // 迭代过程中,判断版本号有无被修改,有被修改,抛 ConcurrentModificationException
  27. checkForComodification();
  28. int i = cursor - 1;
  29. if (i < 0)
  30. throw new NoSuchElementException();
  31. Object[] elementData = ArrayList.this.elementData;
  32. if (i >= elementData.length)
  33. throw new ConcurrentModificationException();
  34. cursor = i;
  35. return (E) elementData[lastRet = i];
  36. }
  37. public void set(E e) {
  38. if (lastRet < 0)
  39. throw new IllegalStateException();
  40. checkForComodification();
  41. try {
  42. ArrayList.this.set(lastRet, e);
  43. } catch (IndexOutOfBoundsException ex) {
  44. throw new ConcurrentModificationException();
  45. }
  46. }
  47. public void add(E e) {
  48. checkForComodification();
  49. try {
  50. int i = cursor;
  51. ArrayList.this.add(i, e);
  52. cursor = i + 1;
  53. lastRet = -1;
  54. expectedModCount = modCount;
  55. } catch (IndexOutOfBoundsException ex) {
  56. throw new ConcurrentModificationException();
  57. }
  58. }
  59. }

ArrayList 的其他方法

ArrayList.toArray() 的底层源码实现如下:

  1. public Object[] toArray() {
  2. return Arrays.copyOf(elementData, size);
  3. }
  4. public <T> T[] toArray(T[] a) {
  5. // 如果 a 的空间不够,新拷贝一个数组返回
  6. if (a.length < size)
  7. // Make a new array of a's runtime type, but my contents:
  8. return (T[]) Arrays.copyOf(elementData, size, a.getClass());
  9. System.arraycopy(elementData, 0, a, 0, size);
  10. if (a.length > size)
  11. a[size] = null;
  12. return a;
  13. }

ArrayList 的常见问题

说一下你对 ArrayList 的了解

底层数据结构
ArrayList 的底层数据结构是一个 Object 类型的数组,add 的元素被存储在其中。


构造器相关
若使用默认构造器构造一个 ArrayList 时,这个数组为 null,此时并不会被初始化,只有当第一次 add 元素时才会执行初始化扩容操作,此时数组大小被初始化为 10。
若使用给定初始容量的构造器构造一个 ArrayList 时,就直接在构造器中 new 一个给定大小的 Object 类型的数组。
若要构造一个包含指定 Collection 集合中元素的 ArrayList 时,在构造器中获取指定集合的底层数组的副本,该 ArrayList 的底层数组指向该副本。


数组自动扩容
ArrayList 在每次执行 add 时,都会先执行 ensureCapacityInternal(size + 1); 确保数组有容量将要 add 的元素存储在底层数组【我们期望数组容量最小为 (size + 1)】,若当前数组大小 < 我们期望的数组容量时,执行 grow(minCapacity);,该方法中是真正的扩容逻辑。
如果将要扩容后的数组容量 > MAX_ARRAY_SIZE【jvm 所能分配的数组长度的最大值】的话,则用 期望的数组容量 和 MAX_ARRAY_SIZE 作比较,最终在 期望的数组容量、MAX_VALUE、Integer.MAX_VALUE 三者中取一个合适的值。