• JDK集合源码之ArrayList解析


    1. ArrayList 继承体系

    在这里插入图片描述

     ArrayList 又称动态数组,底层是基于数组实现的List,与数组的区别在于,其具备动态扩展能力。从继承体系图中可看出ArrayList

    ArrayList实现了List接口,是顺序容器,即元素存放的数据与放进去的顺序相同,允许放入 null 元素,底层通过数组实现。除该类未实现同步外,其余跟Vector大 致相同。每个ArrayList都有一个容量(capacity),表示底层数组的实际大小,容器内存储元素的个数不能多于当前容量。当向容器中添加元素时,如果容量不足,容 器会自动增大底层数组的大小。前面已经提过,Java泛型只是编译器提供的语法糖,所以这里的数组是一个Object数组,以便能够容纳任何类型的对象。

    size(), isEmpty(), get(), set()方法均能在常数时间内完成,add()方法的时间开销跟插入位置有关,addAll()方法的时间开销跟添加元素的个数成正比。其余方法大都是 线性时间。 为追求效率,ArrayList没有实现同步(synchronized),如果需要多个线程并发访问,用户可以手动同步,也可使用Vector替代。

    size(), isEmpty(), get(), set()方法均能在常数时间内完成,add()方法的时间开销跟插入位置有关,addAll()方法的时间开销跟添加元素的个数成正比。其余方法大都是线性时间。

    为追求效率,ArrayList没有实现同步(synchronized),如果需要多个线程并发访问,用户可以手动同步,也可使用Vector替代。

    ArrayList实现了List接口,是顺序容器,即元素存放的数据与放进去的顺序相同,允许放入null元素,底层通过数组实现。除该类未实现同步外,其余跟Vector大致相同。每个ArrayList都有一个容量(capacity),表示底层数组的实际大小,容器内存储元素的个数不能多于当前容量。当向容器中添加元素时,如果容量不足,容器会自动增大底层数组的大小。前面已经提过,Java泛型只是编译器提供的语法糖,所以这里的数组是一个Object数组,以便能够容纳任何类型的对象。

    实现了List, RandomAccess, Cloneable, java.io.Serializable等接口
    实现了List,具备基础的添加、删除、遍历等操作
    实现了RandomAccess,具备随机访问的能力
    实现了Cloneable,可以被克隆(浅拷贝) list.clone()
    实现了Serializable,可以被序列化

    2. ArrayList 实现Cloneable,RandomAccess,Serializable接口

    实现Cloneable接口,可以被浅拷贝

    1. /**
    2. * Returns a shallow copy of this <tt>ArrayList</tt> instance. (The
    3. * elements themselves are not copied.)
    4. * 返回此<tt> ArrayList </ tt>实例的拷贝副本。 (元素本身不会被复制。)
    5. *
    6. * @return a clone of this <tt>ArrayList</tt> instance
    7. */
    8. public Object clone() {
    9. try {
    10. ArrayList<?> v = (ArrayList<?>) super.clone();
    11. // 拷贝
    12. v.elementData = Arrays.copyOf(elementData, size);
    13. v.modCount = 0;
    14. return v;
    15. } catch (CloneNotSupportedException e) {
    16. // this shouldn't happen, since we are Cloneable
    17. throw new InternalError(e);
    18. }
    19. }

    在java语言中,对象实现 Cloneable 接口时,能够对其进行深拷贝和浅拷贝,这里简述下,深拷贝和浅拷贝的区别:

    下面来看浅拷贝实例:

    1. @Test
    2. public void test02() {
    3. /**
    4. * 简单演示ArrayList 浅拷贝:
    5. */
    6. ArrayList list = new ArrayList();
    7. //User 对象实例化
    8. User user = new User("csp");
    9. list.add("abc");// list添加简单字符类型
    10. list.add(user);// list添加对象类型
    11. System.out.println("------------原始ArrayList集合------------");
    12. System.out.println("list:"+list);
    13. // 浅拷贝
    14. ArrayList clone = (ArrayList) list.clone();
    15. System.out.println("------------浅拷贝后得到的新ArrayList集合------------");
    16. System.out.println("二者地址是否相同:" + (list == clone));
    17. System.out.println("------------未修改list中的User属性之前------------");
    18. System.out.println("clone:"+clone);
    19. System.out.println("------------当修改list中的User属性之后------------");
    20. User u = (User) list.get(1);
    21. u.setName("csp1999");
    22. System.out.println("clone:"+clone);
    23. System.out.println("clone中的user对象和原始list中的user对象地址是否相同:"+(list.get(1)==clone.get(1)));
    24. }
    1. ------------原始ArrayList集合------------
    2. list:[abc, User{name='csp'}]
    3. ------------浅拷贝后得到的新ArrayList集合------------
    4. 二者地址是否相同:false
    5. ------------未修改list中的User属性之前------------
    6. clone:[abc, User{name='csp'}]
    7. ------------当修改list中的User属性之后------------
    8. clone:[abc, User{name='csp1999'}]
    9. clone中的user对象和原始list中的user对象地址是否相同:true

    由结果可得出结论:

    当最初的list 集合被克隆之后,实际上是产生了一个新的ArrayList对象,二者地址引用不相同
    当从list集合中获取到user对象并修改其属性之后,clone集合中的user属性也对应发生了改变,这就说明,clone在复制list集合时,对复杂的对象类型数据元素,只是拷贝了其地址引用,并未对其进行新建对象
    因此,执行list.get(1)==clone.get(1))代码的时候,二者存储的user是同一个user对象,地址和数据均相同
    而如果进行深拷贝时,就会在list被克隆新创建克隆对象时,对其存储的复杂对象类型也进行对象新创建,复杂对象类型数据获得新的地址引用,而不是像浅拷贝那样,仅仅拷贝了复杂对象类型的地址引用。

    实现RandomAccess接口,可以提高随机访问列表的效率
    ArrayList 实现了RandomAccess接口,因此当执行随机访问列表的时候,效率要高于顺序访问列表的效率,我们来看一个例子:

    1. @Test
    2. public void test03() {
    3. ArrayList arrayList = new ArrayList();
    4. for (int i=0;i<=99999;i++){// 集合中添加十万条数据
    5. arrayList.add(i);
    6. }
    7. // 测试随机访问的效率:
    8. long startTime = System.currentTimeMillis();
    9. for (int i = 0; i < arrayList.size(); i++) {// 随机访问
    10. // 从集合中访问每一个元素
    11. arrayList.get(i);
    12. }
    13. long endTime = System.currentTimeMillis();
    14. System.out.println("执行随机访问所用时间:"+(endTime-startTime));
    15. // 测试顺序访问的效率:
    16. startTime = System.currentTimeMillis();
    17. Iterator it = arrayList.iterator();// 顺序访问,也可以使用增强for
    18. while (it.hasNext()){
    19. // 从集合中访问每一个元素
    20. it.next();
    21. }
    22. endTime = System.currentTimeMillis();
    23. System.out.println("执行顺序访问所用时间:"+(endTime-startTime));
    24. }
    1. 执行随机访问所用时间:1
    2. 执行顺序访问所用时间:3

    可以看出实现RandomAccess接口的ArrayList 进行随机访问的效率高于进行顺序访问的效率。
    作为对比我们再来看一下未实现RandomAccess接口的LinkedList集合,测试随机访问和顺序访问列表的效率对比:

    1. @Test
    2. public void test04() {
    3. LinkedList linkedList = new LinkedList();
    4. for (int i=0;i<=99999;i++){// 集合中添加十万条数据
    5. linkedList.add(i);
    6. }
    7. // 测试随机访问的效率:
    8. long startTime = System.currentTimeMillis();
    9. for (int i = 0; i < linkedList.size(); i++) {// 随机访问
    10. // 从集合中访问每一个元素
    11. linkedList.get(i);
    12. }
    13. long endTime = System.currentTimeMillis();
    14. System.out.println("执行随机访问所用时间:"+(endTime-startTime));
    15. // 测试顺序访问的效率:
    16. startTime = System.currentTimeMillis();
    17. Iterator it = linkedList.iterator();// 顺序访问,也可以使用增强for
    18. while (it.hasNext()){
    19. // 从集合中访问每一个元素
    20. it.next();
    21. }
    22. endTime = System.currentTimeMillis();
    23. System.out.println("执行顺序访问所用时间:"+(endTime-startTime));
    24. }
    1. 执行随机访问所用时间:4601
    2. 执行顺序访问所用时间:2

    由结果可得出结论,没有实现RandomAccess接口的LinkedList集合,测试随机访问的效率远远低于顺序访问。

    3. ArrayList 属性

    1. /**
    2. * Default initial capacity.
    3. * 默认容量
    4. */
    5. private static final int DEFAULT_CAPACITY = 10;
    6. /**
    7. * Shared empty array instance used for empty instances.
    8. * 空数组,如果传入的容量为0时使用
    9. */
    10. private static final Object[] EMPTY_ELEMENTDATA = {};
    11. /**
    12. * Shared empty array instance used for default sized empty instances.
    13. * We distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when first element is added.
    14. * 默认空容量的数组,长度为0,传入容量时使用,添加第一个元素的时候会重新初始为默认容量大小
    15. */
    16. private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    17. /**
    18. * The array buffer into which the elements of the ArrayList are stored.
    19. * The capacity of the ArrayList is the length of this array buffer. Any
    20. * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
    21. * will be expanded to DEFAULT_CAPACITY when the first element is added.
    22. * 集合中真正存储数据元素的数组容器
    23. */
    24. transient Object[] elementData; // non-private to simplify nested class access
    25. /**
    26. * The size of the ArrayList (the number of elements it contains).
    27. * 集合中元素的个数
    28. * @serial
    29. */
    30. private int size;

    DEFAULT_CAPACITY:集合的默认容量,默认为10,通过new ArrayList()创建List集合实例时的默认容量是10。
    EMPTY_ELEMENTDATA:空数组,通过new ArrayList(0)创建List集合实例时用的是这个空数组。
    DEFAULTCAPACITY_EMPTY_ELEMENTDATA:默认容量空数组,这种是通过new ArrayList()无参构造方法创建集合时用的是这个空数组,与EMPTY_ELEMENTDATA的区别是在添加第一个元素时使用这个空数组的会初始化为DEFAULT_CAPACITY(10)个元素。
    elementData:存储数据元素的数组,使用transient修饰,该字段不被序列化。
    size:存储数据元素的个数,elementData数组的长度并不是存储数据元素的个数。

    自动扩容

    每当向数组中添加元素时,都要去检查添加后元素的个数是否会超出当前数组的长度,如果超出,数组将会进行扩容,以满足添加数据的需求。数组扩容通过一个公 开的方法ensureCapacity(int minCapacity)来实现。在实际添加大量元素前,我也可以使用ensureCapacity来手动增加ArrayList实例的容量,以减少递增式再分配的数 量。 数组进行扩容时,会将老数组中的元素重新拷贝一份到新的数组中,每次数组容量的增长大约是其原容量的1.5倍。这种操作的代价是很高的,因此在实际使用时,我 们应该尽量避免数组容量的扩张。当我们可预知要保存的元素的多少时,要在构造ArrayList实例时,就指定其容量,以避免数组扩容的发生。或者根据实际需求,通 过调用ensureCapacity方法来手动增加ArrayList实例的容量。

    4. ArrayList 构造方法

    ArrayList(int initialCapacity)有参构造方法

    1. /**
    2. * Constructs an empty list with the specified initial capacity.
    3. * 构造具有指定初始容量的空数组
    4. *
    5. * @param initialCapacity the initial capacity of the list 列表的初始容量
    6. * @throws IllegalArgumentException if the specified initial capacity is negative
    7. *
    8. * 传入初始容量,如果大于0就初始化elementData为对应大小,如果等于0就使用EMPTY_ELEMENTDATA空数组,
    9. * 如果小于0抛出异常。
    10. */
    11. // ArrayList(int initialCapacity)构造方法
    12. public ArrayList(int initialCapacity) {
    13. if (initialCapacity > 0) {
    14. this.elementData = new Object[initialCapacity];
    15. } else if (initialCapacity == 0) {
    16. this.elementData = EMPTY_ELEMENTDATA;
    17. } else {
    18. throw new IllegalArgumentException("不合理的初识容量: " +
    19. initialCapacity);
    20. }
    21. }

    ArrayList()空参构造方法

    1. /**
    2. * Constructs an empty list with an initial capacity of ten.
    3. * 构造一个初始容量为10的空数组
    4. *
    5. * 不传初始容量,初始化为DEFAULTCAPACITY_EMPTY_ELEMENTDATA空数组,
    6. * 会在添加第一个元素的时候扩容为默认的大小,即10。
    7. */
    8. public ArrayList() {
    9. this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    10. }

    ArrayList(Collection c)有参构造方法

    1. /**
    2. * Constructs a list containing the elements of the specified
    3. * collection, in the order they are returned by the collection's
    4. * iterator.
    5. * 把传入集合的元素初始化到ArrayList中
    6. *
    7. * @param c the collection whose elements are to be placed into this list
    8. * @throws NullPointerException if the specified collection is null
    9. */
    10. public ArrayList(Collection<? extends E> c) {
    11. // 将构造方法中的集合参数转换成数组
    12. elementData = c.toArray();
    13. if ((size = elementData.length) != 0) {
    14. // 检查c.toArray()返回的是不是Object[]类型,如果不是,重新拷贝成Object[].class类型
    15. if (elementData.getClass() != Object[].class)
    16. // 数组的创建与拷贝
    17. elementData = Arrays.copyOf(elementData, size, Object[].class);
    18. } else {
    19. // 如果c是空的集合,则初始化为空数组EMPTY_ELEMENTDATA
    20. this.elementData = EMPTY_ELEMENTDATA;
    21. }
    22. }

    5. ArrayList 相关操作方法

    add(E e)添加元素到集合中

    添加元素到末尾,平均时间复杂度为O(1):

    1. /**
    2. * Appends the specified element to the end of this list.
    3. * 添加元素到末尾,平均时间复杂度为O(1)
    4. * * @param e element to be appended to this list
    5. * @return <tt>true</tt> (as specified by {@link Collection#add})
    6. */
    7. public boolean add(E e) {
    8. // 每加入一个元素,minCapacity大小+1,并检查是否需要扩容
    9. ensureCapacityInternal(size + 1); // Increments modCount!!
    10. // 把元素插入到最后一位
    11. elementData[size++] = e;
    12. return true;
    13. }
    14. // 计算最小容量
    15. private static int calculateCapacity(Object[] elementData, int minCapacity) {
    16. // 如果是空数组DEFAULTCAPACITY_EMPTY_ELEMENTDATA
    17. if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
    18. // 返回DEFAULT_CAPACITY 和 minCapacity的大一方
    19. return Math.max(DEFAULT_CAPACITY, minCapacity);
    20. }
    21. return minCapacity;
    22. }
    23. // 检查是否需要扩容
    24. private void ensureCapacityInternal(int minCapacity) {
    25. ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    26. }
    27. private void ensureExplicitCapacity(int minCapacity) {
    28. modCount++;// 数组结构被修改的次数+1
    29. // overflow-conscious code 储存元素的数据长度小于需要的最小容量时
    30. if (minCapacity - elementData.length > 0)
    31. // 扩容
    32. grow(minCapacity);
    33. }
    34. /**
    35. * 扩容
    36. * Increases the capacity to ensure that it can hold at lea
    37. * number of elements specified by the minimum capacity arg
    38. * 增加容量以确保它至少可以容纳最小容量参数指定的元素数量
    39. * @param minCapacity the desired minimum capacity
    40. */
    41. private void grow(int minCapacity) {
    42. // 原来的容量
    43. int oldCapacity = elementData.length;
    44. // 新容量为旧容量的1.5倍
    45. int newCapacity = oldCapacity + (oldCapacity >> 1);
    46. // 如果新容量发现比需要的容量还小,则以需要的容量为准
    47. if (newCapacity - minCapacity < 0)
    48. newCapacity = minCapacity;
    49. // 如果新容量已经超过最大容量了,则使用最大容量
    50. if (newCapacity - MAX_ARRAY_SIZE > 0)
    51. newCapacity = hugeCapacity(minCapacity);
    52. // 以新容量拷贝出来一个新数组
    53. elementData = Arrays.copyOf(elementData, newCapacity);
    54. }
    55. // 使用最大容量
    56. private static int hugeCapacity(int minCapacity) {
    57. if (minCapacity < 0) // overflow
    58. throw new OutOfMemoryError();
    59. return (minCapacity > MAX_ARRAY_SIZE) ?
    60. Integer.MAX_VALUE :
    61. MAX_ARRAY_SIZE;
    62. }

    执行流程:

    检查是否需要扩容;

    如果elementData等于DEFAULTCAPACITY_EMPTY_ELEMENTDATA则初始化容量大小为DEFAULT_CAPACITY;
    新容量是老容量的1.5倍(oldCapacity + (oldCapacity >> 1)),如果加了这么多容量发现比需要的容量还小,则以需要的容量为准;
    创建新容量的数组并把老数组拷贝到新数组;

    add(int index, E element)添加元素到指定位置

    添加元素到指定位置,平均时间复杂度为O(n):

    1. /**
    2. * Inserts the specified element at the specified position in this
    3. * list. Shifts the element currently at that position (if any) and
    4. * any subsequent elements to the right (adds one to their indices).
    5. * 添加元素到指定位置,平均时间复杂度为O(n)。
    6. * * @param index 指定元素要插入的索引
    7. * @param element 要插入的元素
    8. * @throws IndexOutOfBoundsException {@inheritDoc}
    9. */
    10. public void add(int index, E element) {
    11. // 检查是否越界
    12. rangeCheckForAdd(index);
    13. // 检查是否需要扩容
    14. ensureCapacityInternal(size + 1); // Increments modCount!!
    15. // 将inex及其之后的元素往后挪一位,则index位置处就空出来了
    16. // **进行了size-索引index次操作**
    17. System.arraycopy(elementData, index, elementData, index + 1,
    18. size - index);
    19. // 将元素插入到index的位置
    20. elementData[index] = element;
    21. // 元素数量增1
    22. size++;
    23. }
    24. /**
    25. * A version of rangeCheck used by add and addAll.
    26. * add和addAll方法使用的rangeCheck版本
    27. */
    28. // 检查是否越界
    29. private void rangeCheckForAdd(int index) {
    30. if (index > size || index < 0)
    31. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    32. }

    执行流程:

    • 检查索引是否越界;
    • 检查是否需要扩容;
    • 把插入索引位置后的元素都往后挪一位;
    • 在插入索引位置放置插入的元素;
    • 元素数量增1;

    addAll(Collection c)添加所有集合参数中的所有元素

    求两个集合的并集:

    1. /**
    2. * Appends all of the elements in the specified collection to the end of
    3. * this list, in the order that they are returned by the
    4. * specified collection's Iterator. The behavior of this operation is
    5. * undefined if the specified collection is modified while the operation
    6. * is in progress. (This implies that the behavior of this call is
    7. * undefined if the specified collection is this list, and this
    8. * list is nonempty.)
    9. * 将集合c中所有元素添加到当前ArrayList中
    10. * * @param c collection containing elements to be added to this list
    11. * @return <tt>true</tt> if this list changed as a result of the call
    12. * @throws NullPointerException if the specified collection is null
    13. */
    14. public boolean addAll(Collection<? extends E> c) {
    15. // 将集合c转为数组
    16. Object[] a = c.toArray();
    17. int numNew = a.length;
    18. // 检查是否需要扩容
    19. ensureCapacityInternal(size + numNew); // Increments modCount
    20. // 将c中元素全部拷贝到数组的最后
    21. System.arraycopy(a, 0, elementData, size, numNew);
    22. // 集合中元素的大小增加c的大小
    23. size += numNew;
    24. // 如果c不为空就返回true,否则返回false
    25. return numNew != 0;
    26. }

    执行流程:

    • 拷贝c中的元素到数组a中;
    • 检查是否需要扩容;
    • 把数组a中的元素拷贝到elementData的尾部;

    get(int index)获取指定索引位置的元素

    获取指定索引位置的元素,时间复杂度为O(1)。

    1. /**
    2. * Returns the element at the specified position in this list.
    3. * * @param index index of the element to return
    4. * @return the element at the specified position in this list
    5. * @throws IndexOutOfBoundsException {@inheritDoc}
    6. */
    7. public E get(int index) {
    8. // 检查是否越界
    9. rangeCheck(index);
    10. // 返回数组index位置的元素
    11. return elementData(index);
    12. }
    13. /**
    14. * Checks if the given index is in range. If not, throws an appropriate
    15. * runtime exception. This method does *not* check if the index is
    16. * negative: It is always used immediately prior to an array access,
    17. * which throws an ArrayIndexOutOfBoundsException if index is negative.
    18. * 检查给定的索引是否在集合有效元素数量范围内
    19. */
    20. private void rangeCheck(int index) {
    21. if (index >= size)
    22. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    23. }
    24. @SuppressWarnings("unchecked")
    25. E elementData(int index) {
    26. return (E) elementData[index];
    27. }

    执行流程:

    • 检查索引是否越界,这里只检查是否越上界,如果越上界抛出IndexOutOfBoundsException异常,如果越下界抛出的是ArrayIndexOutOfBoundsException异常。
    • 返回索引位置处的元素;

    remove(int index)删除指定索引位置的元素

    删除指定索引位置的元素,时间复杂度为O(n)。

    1. /**
    2. * Removes the element at the specified position in this list.
    3. * Shifts any subsequent elements to the left (subtracts one from their
    4. * indices).
    5. * 删除指定索引位置的元素,时间复杂度为O(n)。
    6. * * @param index the index of the element to be removed
    7. * @return the element that was removed from the list
    8. * @throws IndexOutOfBoundsException {@inheritDoc}
    9. */
    10. public E remove(int index) {
    11. // 检查是否越界
    12. rangeCheck(index);
    13. // 集合底层数组结构修改次数+1
    14. modCount++;
    15. // 获取index位置的元素
    16. E oldValue = elementData(index);
    17. int numMoved = size - index - 1;
    18. // 如果index不是最后一位,则将index之后的元素往前挪一位
    19. if (numMoved > 0)
    20. // **进行了size-索引index-1次操作**
    21. System.arraycopy(elementData, index + 1, elementData, index,
    22. numMoved);
    23. // 将最后一个元素删除,帮助GC
    24. elementData[--size] = null; // clear to let GC do its work
    25. // 返回旧值
    26. return oldValue;
    27. }

    执行流程:

    • 检查索引是否越界;
    • 获取指定索引位置的元素;
    • 如果删除的不是最后一位,则其它元素往前移一位;
    • 将最后一位置为null,方便GC回收;
    • 返回删除的元素。

    注意:从源码中得出,ArrayList删除元素的时候并没有缩容

    remove(Object o)删除指定元素值的元素

    删除指定元素值的元素,时间复杂度为O(n)。

    1. /**
    2. * Removes the first occurrence of the specified element from this list,
    3. * if it is present. If the list does not contain the element, it is
    4. * unchanged. More formally, removes the element with the lowest index
    5. * <tt>i</tt> such that
    6. * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
    7. * (if such an element exists). Returns <tt>true</tt> if this list
    8. * contained the specified element (or equivalently, if this list
    9. * changed as a result of the call).
    10. * 删除指定元素值的元素,时间复杂度为O(n)。
    11. * * @param o element to be removed from this list, if present
    12. * 要从此列表中删除的元素(如果存在的话)
    13. * @return <tt>true</tt> if this list contained the specified element
    14. */
    15. public boolean remove(Object o) {
    16. if (o == null) {
    17. // 遍历整个数组,找到元素第一次出现的位置,并将其快速删除
    18. for (int index = 0; index < size; index++)
    19. // 如果要删除的元素为null,则以null进行比较,使用==
    20. if (elementData[index] == null) {
    21. fastRemove(index);
    22. return true;
    23. }
    24. } else {
    25. // 遍历整个数组,找到元素第一次出现的位置,并将其快速删除
    26. for (int index = 0; index < size; index++)
    27. // 如果要删除的元素不为null,则进行比较,使用equals()方法
    28. if (o.equals(elementData[index])) {
    29. fastRemove(index);
    30. return true;
    31. }
    32. }
    33. return false;
    34. }
    35. /*
    36. * Private remove method that skips bounds checking and does not
    37. * return the value removed.
    38. * 专用的remove方法,跳过边界检查,并且不返回删除的值。
    39. */
    40. private void fastRemove(int index) {
    41. // 少了一个越界的检查
    42. modCount++;
    43. // 如果index不是最后一位,则将index之后的元素往前挪一位
    44. int numMoved = size - index - 1;
    45. if (numMoved > 0)
    46. System.arraycopy(elementData, index + 1, elementData, index,
    47. numMoved);
    48. // 将最后一个元素删除,帮助GC
    49. elementData[--size] = null; // clear to let GC do its work
    50. }

    执行流程:

    • 找到第一个等于指定元素值的元素;
    • 快速删除;
      fastRemove(int index)相对于remove(int index)少了检查索引越界的操作,可见jdk将性能优化到极致。

    retainAll(Collection c)求两个集合的交集

    1. /**
    2. * 求两个集合的交集
    3. * Retains only the elements in this list that are contained in the
    4. * specified collection. In other words, removes from this list all
    5. * of its elements that are not contained in the specified collection.
    6. * * @param c collection containing elements to be retained in this list
    7. * @return {@code true} if this list changed as a result of the call
    8. * @throws ClassCastException if the class of an element of this list
    9. * is incompatible with the specified collection
    10. * (<a href="Collection.html#optional-restrictions">opti
    11. * @throws NullPointerException if this list contains a null element and the
    12. * specified collection does not permit null elements
    13. * (<a href="Collection.html#optional-restrictions">opti
    14. * or if the specified collection is null
    15. * @see Collection#contains(Object)
    16. */
    17. public boolean retainAll(Collection<?> c) {
    18. // 集合c不能为null
    19. Objects.requireNonNull(c);
    20. // 调用批量删除方法,这时complement传入true,表示删除不包含在c中的元素
    21. return batchRemove(c, true);
    22. }
    23. /**
    24. * 批量删除元素
    25. * complement为true表示删除c中不包含的元素
    26. * complement为false表示删除c中包含的元素
    27. * @param c
    28. * @param complement
    29. * @return
    30. */
    31. private boolean batchRemove(Collection<?> c, boolean complement) {
    32. final Object[] elementData = this.elementData;
    33. /**
    34. * 使用读写两个指针同时遍历数组
    35. * 读指针每次自增1,写指针放入元素的时候才加1
    36. * 这样不需要额外的空间,只需要在原有的数组上操作就可以了
    37. */
    38. int r = 0, w = 0;
    39. boolean modified = false;
    40. try {
    41. // 遍历整个数组,如果c中包含该元素,则把该元素放到写指针的位置(以complement为准)
    42. for (; r < size; r++)
    43. if (c.contains(elementData[r]) == complement)
    44. elementData[w++] = elementData[r];
    45. } finally {
    46. // 正常来说r最后是等于size的,除非c.contains()抛出了异常
    47. if (r != size) {
    48. // 如果c.contains()抛出了异常,则把未读的元素都拷贝到写指针之后
    49. System.arraycopy(elementData, r,
    50. elementData, w,
    51. size - r);
    52. w += size - r;
    53. }
    54. if (w != size) {
    55. // 将写指针之后的元素置为空,帮助GC
    56. for (int i = w; i < size; i++)
    57. elementData[i] = null;
    58. modCount += size - w;
    59. // 新大小等于写指针的位置(因为每写一次写指针就加1,所以新大小正好等于写指针的位置)
    60. size = w;
    61. modified = true;
    62. }
    63. }
    64. // 有修改返回true
    65. return modified;
    66. }

    执行流程:

    • 遍历elementData数组;
    • 如果元素在c中,则把这个元素添加到elementData数组的w位置并将w位置往后移一位;
    • 遍历完之后,w之前的元素都是两者共有的,w之后(包含)的元素不是两者共有的;
    • 将w之后(包含)的元素置为null,方便GC回收;

    ArrayList所使用的toString()方法分析:

    我们都知道ArrayList集合是可以直接使用toStrin()方法的,那么我们来挖一下ArrayList的toString方法如何实现的:
    在ArrayList源码中并没有直接的toString()方法,我们需要到其父类AbstractList的父类AbstractCollection中寻找:
     

    1. /**
    2. * Returns a string representation of this collection. The string
    3. * representation consists of a list of the collection's elements in the
    4. * order they are returned by its iterator, enclosed in square brackets
    5. * (<tt>"[]"</tt>). Adjacent elements are separated by the characters
    6. * <tt>", "</tt> (comma and space). Elements are converted to strings as
    7. * by {@link String#valueOf(Object)}.
    8. *
    9. * @return a string representation of this collection
    10. */
    11. public String toString() {
    12. Iterator<E> it = iterator();// 获取迭代器
    13. if (! it.hasNext())//如果为空直接返回
    14. return "[]";
    15. // StringBuilder进行字符串拼接
    16. StringBuilder sb = new StringBuilder();
    17. sb.append('[');
    18. for (;;) {// 无限循环 == while(true)
    19. E e = it.next();// 迭代器 next方法取元素,并将光标后移
    20. sb.append(e == this ? "(this Collection)" : e);// 三元判断
    21. if (! it.hasNext())
    22. return sb.append(']').toString();// 没有元素了,则拼接右括号
    23. sb.append(',').append(' ');// 还有元素存在
    24. }
    25. }

    Fail-Fast机制:

    ArrayList也采用了快速失败的机制,通过记录modCount参数来实现。在面对并发的修改时,迭代器很快就会完全失败,而不是冒着在将来某个不确定时间发生任意 不确定行为的风险。

  • 相关阅读:
    系统架构设计师【第19章】: 大数据架构设计理论与实践 (核心总结)
    1.jdk,数据类型,运算符
    Pytorch代码入门学习之分类任务(三):定义损失函数与优化器
    [附源码]计算机毕业设计springboot网咖管理系统
    Ajax加强
    手机拍摄全景图并且使用Threejs实现VR全景,超简单
    大数据平台之数据治理
    MATLAB BP神经网络 笔记整理
    导航守卫和拦截器
    4.2 K8S超级完整安装配置
  • 原文地址:https://blog.csdn.net/weixin_63566550/article/details/125624210