2 ArrayList 详解

List 是有序、可重复的容器。List中每个元素都有索引标记,可以根据元素的索引标记访问元素,从而精确控制这些元素。

List 接口常用的实现类:ArrayList、LinkedList、Vector。

ArrayList 底层是用数组实现。特点:查询效率高,增删效率低,线程不安全。增删操作较多的场景使用LinkedList,线程安全使用Vector 或者封装的线程安全集合类。

 

1、ArrayList

public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable

ArrayList 通过动态数组实现,且实现了所有可选列表操作,允许包括null在内的所有元素。除了实现List接口外,此类还提供一些方法来操作内部用来存储列表的数组的大小。

2、源码解析

ArrayList 由动态对象数组实现,默认构造方法创建一个空数组。第一次添加元素时,容量扩充为10,之后的扩充算法是原容量1.5倍。

(1) 添加方法

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

 

(2) 扩容方法

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

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

(3) 删除方法

    public E remove(int index) {
        rangeCheck(index);

        modCount++;
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }

3 ArrayList的特点

3.1 动态数组不适合做删除、插入操作。

3.2 为了防止数组动态扩充过多,建议创建时给定初始容量。

3.3 多线程不安全,适合在单线程使用。

3.4 建议存储同类型的对象。

 

4 ArrayList 扩展方法

addAll(Collection c)

removeAll(Collection c)

retainAll(Collection c)

containsALll(Collection c)

indexOf(Object o)

lastIndexOf(Object o)

 

猜你喜欢

转载自www.cnblogs.com/Latiny/p/10705934.html