4. ArrayList

ArrayList即底层基于数组的线性表

大多数应用开发中需要List的场合使用它即可。 相比于数组它有自动扩容的优点。大部分情况下没必要为了提高一点点性能不使用ArrayList而使用原始数组。

特点:
1)初始化时容量默认是10, 可通过构造函数指定,达到优化效果。
2)当容量不够时会自动扩容,扩容为原来的1.5倍。
3)新增/删除元素平均时间复杂度: O(n), 因为涉及到元素的移位
4)查找元素平均时间复杂度:O(n);当知道元素下标时时间复杂度是O(1)

ArrayList源码分析(JDK17)
  1. 实现List接口和RandomAccess接口
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable

RandomAccess是一个标记接口,没有具体方法,表示该类的实例支持随机访问,即支持根据下标快速定位元素,查询时间复杂度为O(1)

  1. 构造器

    /**
     * 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
	 * 从构造函数的实现上看,ArrayList的底层维护了一个Object数组,
	 * 如果指定了capacity,则初始化数组的长度就是capacity
     */
    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.   默认构造器
     */
    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.
     * 以另一个集合初始化本ArrayList, 这个构造器是所有集合实现类
     * 约定都需要有,方便集合类型转换。
     * @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) {
        Object[] a = c.toArray();
        if ((size = a.length) != 0) {
            if (c.getClass() == ArrayList.class) {
                elementData = a;
            } else {
                elementData = Arrays.copyOf(a, size, Object[].class);
            }
        } else {
            // replace with empty array.
            elementData = EMPTY_ELEMENTDATA;
        }
    }
  1. 新增逻辑(包括扩容)
    /**
     * Inserts the specified element at the specified position in this
     * list. Shifts the element currently at that position (if any) and
     * any subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
        // 待插入索引位置检查,0 <= index <= size()
        // 即:最小的位置为0, 最大的位置为当前集合最后一个元素的下一位
        rangeCheckForAdd(index);
        modCount++;
        final int s;
        Object[] elementData;
        // 当判断出当前数组已满时,执行扩容
        if ((s = size) == (elementData = this.elementData).length)
        	// 扩容逻辑见下文分析
            elementData = grow();
		
		// 待插入位置至最后的元素执行右移
        System.arraycopy(elementData, index,
                         elementData, index + 1,
                         s - index);
        // 将新数据插入到index位置
        elementData[index] = element;
        size = s + 1;
    }
    /**
    
     * Increases the capacity to ensure that it can hold at least the
     * number of elements specified by the minimum capacity argument.
     *
     * 执行数组扩容,扩容后起码要达到最小容量minCapacity。 
     * @param minCapacity the desired minimum capacity
     * @throws OutOfMemoryError if minCapacity is less than zero
     */
    private Object[] grow(int minCapacity) {
        int oldCapacity = elementData.length;
        if (oldCapacity > 0 || elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        	// 扩容后大小要么是minCapacity, 要么是旧容量的两倍,就看两者谁大
            int newCapacity = ArraysSupport.newLength(oldCapacity,
                    minCapacity - oldCapacity, /* minimum growth */
                    oldCapacity >> 1           /* preferred growth */);
            // Arrays.copyOf是一个经典方法,实现数组扩容,并且将旧数据复制进新数组
            return elementData = Arrays.copyOf(elementData, newCapacity);
        } else {
            return elementData = new Object[Math.max(DEFAULT_CAPACITY, minCapacity)];
        }
    }

你可能感兴趣的:(Java集合相关,java)