ArrayList是集合的一种实现,实现了接口List,List接口继承了Collection接口。Collection是所有集合类的父类。ArrayList使用非常广泛,不论是数据库表查询,excel导入解析,还是网站数据爬取都需要使用到,了解ArrayList原理及使用方法显得非常重要。

一. 定义一个ArrayList

  1. //默认创建一个ArrayList集合
  2. List<String> list = new ArrayList<>();
  3. //创建一个初始化长度为100的ArrayList集合
  4. List<String> initlist = new ArrayList<>(100);
  5. //将其他类型的集合转为ArrayList
  6. List<String> setList = new ArrayList<>(new HashSet());

我们读一下源码,看看定义ArrayList的过程到底做了什么?

  1. public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
  2. /**
  3. * Default initial capacity.
  4. */
  5. private static final int DEFAULT_CAPACITY = 10;
  6. /**
  7. * Shared empty array instance used for empty instances.
  8. */
  9. private static final Object[] EMPTY_ELEMENTDATA = {};
  10. /**
  11. * Shared empty array instance used for default sized empty instances. We
  12. * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
  13. * first element is added.
  14. */
  15. private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
  16. /**
  17. * The array buffer into which the elements of the ArrayList are stored.
  18. * The capacity of the ArrayList is the length of this array buffer. Any
  19. * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
  20. * will be expanded to DEFAULT_CAPACITY when the first element is added.
  21. */
  22. transient Object[] elementData; // non-private to simplify nested class access
  23. /**
  24. * The size of the ArrayList (the number of elements it contains).
  25. *
  26. * @serial
  27. */
  28. private int size;
  29. /**
  30. * Constructs an empty list with the specified initial capacity.
  31. *
  32. * @param initialCapacity the initial capacity of the list
  33. * @throws IllegalArgumentException if the specified initial capacity
  34. * is negative
  35. */
  36. public ArrayList(int initialCapacity) {
  37. if (initialCapacity > 0) {
  38. this.elementData = new Object[initialCapacity];
  39. } else if (initialCapacity == 0) {
  40. this.elementData = EMPTY_ELEMENTDATA;
  41. } else {
  42. throw new IllegalArgumentException("Illegal Capacity: "+
  43. initialCapacity);
  44. }
  45. }
  46. /**
  47. * Constructs an empty list with an initial capacity of ten.
  48. */
  49. public ArrayList() {
  50. this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
  51. }
  52. /**
  53. * Constructs a list containing the elements of the specified
  54. * collection, in the order they are returned by the collection's
  55. * iterator.
  56. *
  57. * @param c the collection whose elements are to be placed into this list
  58. * @throws NullPointerException if the specified collection is null
  59. */
  60. public ArrayList(Collection<? extends E> c) {
  61. elementData = c.toArray();
  62. if ((size = elementData.length) != 0) {
  63. // c.toArray might (incorrectly) not return Object[] (see 6260652)
  64. if (elementData.getClass() != Object[].class)
  65. elementData = Arrays.copyOf(elementData, size, Object[].class);
  66. } else {
  67. // replace with empty array.
  68. this.elementData = EMPTY_ELEMENTDATA;
  69. }
  70. }
  71. }

其实源码里面已经很清晰了,ArrayList非线程安全,底层是一个Object[],添加到ArrayList中的数据保存在了elementData属性中。

  • 当调用new ArrayList<>()时,将一个空数组{}赋值给了elementData,这个时候集合的长度size为默认长度0;
  • 当调用new ArrayList<>(100)时,根据传入的长度,new一个Object[100]赋值给elementData,当然如果玩儿的话,传了一个0,那么将一个空数组{}赋值给了elementData;
  • 当调用new ArrayList<>(new HashSet())时,根据源码,我们可知,可以传递任何实现了Collection接口的类,将传递的集合调用toArray()方法转为数组内赋值给elementData;

    注意:在传入集合的ArrayList的构造方法中,有这样一个判断 if (elementData.getClass() != Object[].class), 给出的注释是:c.toArray might (incorrectly) not return Object[] (see 6260652),即调用toArray方法返回的不一定是Object[]类型,查看ArrayList源码

  1. public Object[] toArray() { return Arrays.copyOf(elementData, size);}

我们发现返回的确实是Object[],那么为什么还会有这样的判断呢? 如果有一个类CustomList继承了ArrayList,然后重写了toArray()方法呢。。

  1. public class CustomList<E> extends ArrayList {
  2. @Override
  3. public Integer [] toArray() {
  4. return new Integer[]{1,2};
  5. };
  6. public static void main(String[] args) {
  7. Object[] elementData = new CustomList<Integer>().toArray();
  8. System.out.println(elementData.getClass());
  9. System.out.println(Object[].class);
  10. System.out.println(elementData.getClass() == Object[].class);
  11. }
  12. }

执行结果:

  1. class [Ljava.lang.Integer;
  2. class [Ljava.lang.Object;
  3. false

接着说,如果传入的集合类型和我们定义用来保存添加到集合中值的Object[]类型不一致时,ArrayList做了什么处理?读源码看到,调用了Arrays.copyOf(elementData, size, Object[].class);,继续往下走

  1. public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
  2. T[] copy = ((Object)newType == (Object)Object[].class)
  3. ? (T[]) new Object[newLength]
  4. : (T[]) Array.newInstance(newType.getComponentType(), newLength);
  5. System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength));
  6. return copy;
  7. }

我们发现定义了一个新的数组,将原数组的数据拷贝到了新的数组中去。

二. ArrayList常用方法

ArrayList有很多常用方法,add,addAll,set,get,remove,size,isEmpty等
首先定义了一个ArrayList,

  1. List<String> list = new ArrayList<>(10);
  2. list.add('牛魔王');
  3. list.add('蛟魔王');
  4. ...
  5. list.add('美猴王');

Object[] elementData中数据如下:
java-ArrayList原理及使用 - 图1

1. add(E element)

我们通过源码来看一下add(“白骨精”)到底发生了什么

  1. public boolean add(E e) {
  2. ensureCapacityInternal(size + 1);
  3. // Increments modCount!!
  4. elementData[size++] = e;
  5. return true;
  6. }

首先通过 ensureCapacityInternal(size + 1) 来保证底层Object[]数组有足够的空间存放添加的数据,然后将添加的数据存放到数组对应的位置上,我们看一下是怎么保证数组有足够的空间?

  1. private void ensureCapacityInternal(int minCapacity) {
  2. if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
  3. minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
  4. }
  5. ensureExplicitCapacity(minCapacity);
  6. }
  1. private void ensureExplicitCapacity(int minCapacity) {
  2. modCount++;
  3. // overflow-conscious code
  4. if (minCapacity - elementData.length > 0)
  5. grow(minCapacity);
  6. }

这里首先确定了Object[]足够存放添加数据的最小容量,然后通过 grow(int minCapacity) 来进行数组扩容

  1. private void grow(int minCapacity) {
  2. // overflow-conscious code
  3. int oldCapacity = elementData.length;
  4. int newCapacity = oldCapacity + (oldCapacity >> 1);
  5. if (newCapacity - minCapacity < 0)
  6. newCapacity = minCapacity;
  7. if (newCapacity - MAX_ARRAY_SIZE > 0)
  8. newCapacity = hugeCapacity(minCapacity);
  9. // minCapacity is usually close to size, so this is a win:
  10. elementData = Arrays.copyOf(elementData, newCapacity);
  11. }

扩容规则为“数组当前足够的最小容量 + (数组当前足够的最小容量 / 2)”,即数组当前足够的最小容量 * 1.5,当然有最大值的限制。
因为最开始定义了集合容量为10,故而本次不会进行扩容,直接将第8个位置(从0开始,下标为7)设置为“白骨精”,这时Object[] elementData中数据如下:
java-ArrayList原理及使用 - 图2
还有和add()类似的方法。空间扩容原理都是一样,如:

add("铁扇", 0); //将数组中的元素各自往后移动一位,再将“铁扇”放到第一个位置上; java-ArrayList原理及使用 - 图3 addAll(list..七个葫芦娃); //将集合{七个葫芦娃}放到”白骨精”后,很明显当前数组的容量已经不够,需要扩容了,不执行该句代码了; addAll(list..哪吒三兄弟, 4);//从第五个位置将“哪吒三兄弟”插进去,那么数组第五个位置后的元素都需往后移动三位,数组按规则扩容为18。 java-ArrayList原理及使用 - 图4 指定了插入位置的,会通过rangeCheckForAdd(int index)方法判断是否数组越界

2. set(int index, E element)

因为ArrayList底层是由数组实现的,set实现非常简单,调用 set(8, "猪八戒") 通过传入的数字下标找到对应的位置,替换其中的元素,前提也需要首先判断传入的数组下标是否越界。将“猕猴王”替换为“猪八戒”。

  1. public E set(int index, E element) {
  2. rangeCheck(index);
  3. E oldValue = elementData(index);
  4. elementData[index] = element;
  5. return oldValue;
  6. }

//返回值“猕猴王”,当前数组中数据:
java-ArrayList原理及使用 - 图5

3. get(int index)

ArrayList中get方法也非常简单,通过下标查找即可,同时需要进行了类型转换,因为数组为Object[],前提是需要判断传入的数组下标是否越界。

  1. public E get(int index) {
  2. rangeCheck(index);
  3. return elementData(index);
  4. }
  5. E elementData(int index) {
  6. return (E) elementData[index];
  7. }

调用get(6)返回”哪吒“。

4. remove(int index)

首先说一下ArrayList通过下标删除的方法,我们看一下源码

  1. public E remove(int index) {
  2. rangeCheck(index);
  3. modCount++;
  4. E oldValue = elementData(index);
  5. int numMoved = size - index - 1;
  6. if (numMoved > 0)
  7. System.arraycopy(elementData, index+1, elementData, index, numMoved);
  8. elementData[--size] = null; // clear to let GC do its work
  9. return oldValue;
  10. }

通过源码我们可以看到首先获取了待删除的元素,并最终返回了。其次计算了数组中需要移动的位数 size - index - 1,那么很明显我们可以得出待删除的是最后一个元素的话,移到位数为0,否则移动位数大于0,那么通过数组元素的拷贝来实现往前移动相应位数。
如remove(10),找到的元素为“美猴王”,那么移动位数 = 12-10-1 = 1;此时将原本在第12个位置上(数组下标为11)的“白骨精”往前移动一位,同时设置elementData[11] = null;这里通过设置null值让GC起作用。

5. remove(Object o)

删除ArrayList中的值对象,其实和通过下标删除很相似,只是多了一个步骤,遍历底层数组elementData,通过equals()方法或 == (特殊情况下)来找到要删除的元素,获取其下标,调用remove(int index)一样的代码即可。

  1. public boolean remove(Object o) {
  2. if (o == null) {
  3. for (int index = 0; index < size; index++)
  4. if (elementData[index] == null) {
  5. fastRemove(index);
  6. return true;
  7. }
  8. } else {
  9. for (int index = 0; index < size; index++)
  10. if (o.equals(elementData[index])) {
  11. fastRemove(index);
  12. return true;
  13. }
  14. }
  15. return false;
  16. }

6. 其他方法

size() : 获取集合长度,通过定义在ArrayList中的私有变量size得到
isEmpty():是否为空,通过定义在ArrayList中的私有变量size得到
contains(Object o):是否包含某个元素,通过遍历底层数组elementData,通过equals或==进行判断
clear():集合清空,通过遍历底层数组elementData,设置为null

三. 总结

本文主要讲解了ArrayList原理,从底层数组着手,讲解了ArrayList定义时到底发生了什么,再添加元素时,扩容规则如何,删除元素时,数组的元素的移动方式以及一些常用方法的用途。