ArrayList源码解读

    xiaoxiao2021-03-25  209

    ArrayList的创建

    默认构造函数:

    /** * Constructs an empty list with an initial capacity of ten. */ public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; }

    从上面的DEFAULTCAPACITY_EMPTY_ELEMENTDATA 这个参数的的名字可以看出是默认的空的元素数据。但DEFAULTCAPACITY_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 * first element is added. */ private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    就是一个空的一维数组,不过注释中提到了default sized empty instance,那么default size 到底是多少呢?还是不知道,那么我们可以转换下看思路看能不能从类的属性中找到呢?简单点,望文生义,

    /** * Default initial capacity. */ private static final int DEFAULT_CAPACITY = 10;

    默认是10;

    那么,这算不算是把ArrayList的构造函数阅读完了呢?不算,因为还没有将DEFAULT_CAPACITY 和上面的DEFAULTCAPACITY_EMPTY_ELEMENTDATA一维空数组关联起来,接下来通过阅读另一个构造函数ArrayList(int initialCapacity),看看有什么收获?

    /** * 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); } }

    这段代码很好理解:如果是initialCapacity的数值大于0,就使用initalCapacity开辟数组,如果等于0,就使用默认容量,如果为负数,就抛异常。

    容量,数组中元素的个数,是什么关系?

    ArrayList的添加,重点是add函数

    关键问题: 1. 当数组满了时候,ArrayList是如何处理的?即扩容问题 2. 扩容的过程中使用的怎样的策略,来保证原来数组中的数据不丢失?

    先解决第一个问题:

    /** * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) */ public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; }

    不好理解的是ensureCapacityInternal这个方法,但从字面上理解,就是确保容量足够,那么是怎样确保容量足够呢?如果所有的内存都占用完了呢?怎么办?这个问题也是我被腾讯面试官问到的问题,如果这个方法执行完毕,就可以正常的添加元素了,接下来就看看ensureCapacityInternal这个函数

    private void ensureCapacityInternal(int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); }

    最小容量等于默认容量和最小容量的最大值,那么接下来 ensureExplicitCapacity函数应该就是扩内存容量的,源码中就有grow方法。

    private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity); }

    问题1、modCount作用?2、grow方法内部实现是怎样的? 解决问题1,看源码读注释:

    /** * The number of times this list has been <i>structurally modified</i>. * Structural modifications are those that change the size of the * list, or otherwise perturb it in such a fashion that iterations in * progress may yield incorrect results. * * <p>This field is used by the iterator and list iterator implementation * returned by the {@code iterator} and {@code listIterator} methods. * If the value of this field changes unexpectedly, the iterator (or list * iterator) will throw a {@code ConcurrentModificationException} in * response to the {@code next}, {@code remove}, {@code previous}, * {@code set} or {@code add} operations. This provides * <i>fail-fast</i> behavior, rather than non-deterministic behavior in * the face of concurrent modification during iteration. * * <p><b>Use of this field by subclasses is optional.</b> If a subclass * wishes to provide fail-fast iterators (and list iterators), then it * merely has to increment this field in its {@code add(int, E)} and * {@code remove(int)} methods (and any other methods that it overrides * that result in structural modifications to the list). A single call to * {@code add(int, E)} or {@code remove(int)} must add no more than * one to this field, or the iterators (and list iterators) will throw * bogus {@code ConcurrentModificationExceptions}. If an implementation * does not wish to provide fail-fast iterators, this field may be * ignored. */ protected transient int modCount = 0;

    关键句The number of times this list has been structurally modified.就是说明了modCount的作用是表示修改的次数。至于这个属性的详细作用可以从接下来的注释中去看。

    解决问题2:

    /** * Increases the capacity to ensure that it can hold at least the * number of elements specified by the minimum capacity argument. * * @param minCapacity the desired minimum capacity */ private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; 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); }

    划重点:旧容量等于数组的长度,新容量为旧容量的1.5倍,因为oldCapacity>>1是0.5倍的oldCapacity,再加上原来的oldCapacity,即为1.5倍。如果新容量小于最小容量,那么新容量等于最小容量(就是取两者中的最大值)。接着看,如果新容量大于MAX_ARRAY_SIZE(最大数组容量),那么新的容量就等于hugeCapacity(minCapacity)的容量。关键问题:hugeCapacity方法的作用是?如果以上语句都执行了,就将原来的数组复制到新的容量的数组中。没说的。

    解决hugeCapacity方法的作用是?

    private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) // overflow throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; }

    问题:minCapacity有没有可能小于0,报OutOfMemoryError,个人感觉不可能,因为这个minCapacity还是从add方法中来的。等于size+1;下面就是minCapacity大于MAX_ARRAY_SIZE(最大数组容量),就返回整型数据的最大值,否则就返回MAX_ARRAY_SIZE。就是说普通情况下ArrayList的最大的容量就是Integer.MAX_VALUE。这个ArrayList的峰值。


    总结

    本文主要梳理了ArrayList的扩容策略,简单点,就是当容量不足时,开辟一个新数组,将就数组中的元素都赋值过去。再这个过程中的,难点是开辟新数组的容量如何设置的问题。

    转载请注明原文地址: https://ju.6miu.com/read-3517.html

    最新回复(0)