ArrayList

177 阅读5分钟

数组

  • 数组是在内存中划分出一块连续的地址空间用来进行元素的存储,由于它直接操作内存,所以数组的性能要比集合类更好一些
  • 初始化时必须指定数组大小,并且在后续操作中不能再更改数组的大小

ArrayList

  • 有序、可包含重复元素。
  • 基于数组实现,可动态扩容(1.5倍)
  • 实现RandomAccess接口,可随机访问(根据索引位置访问元素),效率O(1)
  • 尾部插入和删除效率比较高
  • 头部或中间插入和删除效率比较低,需要移动数据,效率O(N)
  • 非线程安全

注意点

1、迭代时删除元素需使用迭代器的删除方法
Iterator<Integet> iter = list.iterator();
while(iter.hasNext()){
    iter.next(); // 删除前需要先调用next方法
    iter.remove();
}

2、List 转 数组
使用此方法: public <T> T[] toArray(T[] a)
例: Integer[] arr = list.toArray(new Integer[0]);

3、数组 转 List
需要新建List,并以Arrays.asList()为参数传入
List<Integer> list = new ArrayList<>(Arrays.asList(arr));

4、线程安全类
可通过Collections工具类的方法包装成线程安全类
List<String> synchronizedList = Collections.synchronizedList(list);

5、subList() 方法返回list的子视图,并非list的子类
List<Integer> sub = new ArrayList<>(list.subList(0,2));

主要成员变量和构造器

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
    //默认初始化容量
    private static final int DEFAULT_CAPACITY = 10;
    //空对象数组
    private static final Object[] EMPTY_ELEMENTDATA = {};
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    //对象数组
    private transient Object[] elementData;
    //集合实际元素个数
    private int size;

    //传入初始容量的构造方法
    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);
        }
    }

    //不带参数的构造方法
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }


    //传入外部集合的构造方法
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }
}

基本方法

Add()

// 尾部添加
public boolean add(E e) {
    //添加前先检查是否需要拓展数组, 此时数组长度最小为size+1
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}

// 数组容量不够,则扩容至1.5倍
// 确保数组容量不小于minCapacity
private void ensureCapacityInternal(int minCapacity) {
    // 无参构造器,并且添加第一个元素时调用,保证第一扩容的最小容量为默认容量10
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
    }

    ensureExplicitCapacity(minCapacity);
}

private void ensureExplicitCapacity(int minCapacity) {
    modCount++;

    // overflow-conscious code
    // 需要的最小容量大于数组实际长度,则需要扩容
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}

// 扩容
private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    // 新容量为原容量的1.5倍
    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);
}

// 指定位置添加元素
public void add(int index, E element) {
    //插入位置范围检查
    rangeCheckForAdd(index);
   
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    //插入位置后面的元素右移一位
    System.arraycopy(elementData, index, elementData, index + 1,
                     size - index);
    elementData[index] = element;
    size++;
}
System.arraycopy()方法实现浅复制,复制引用

// 添加集合,可以添加E的子类型的集合
public boolean addAll(Collection<? extends E> c) {
    Object[] a = c.toArray();
    int numNew = a.length;
    ensureCapacityInternal(size + numNew);  // Increments modCount
    System.arraycopy(a, 0, elementData, size, numNew);
    size += numNew;
    return numNew != 0;
}

public boolean addAll(int index, Collection<? extends E> c) {
    rangeCheckForAdd(index);

    Object[] a = c.toArray();
    int numNew = a.length;
    ensureCapacityInternal(size + numNew);  // Increments modCount

    int numMoved = size - index;
    if (numMoved > 0)
        System.arraycopy(elementData, index, elementData, index + numNew,
                         numMoved);

    System.arraycopy(a, 0, elementData, index, numNew);
    size += numNew;
    return numNew != 0;
}

Get() 和 Set()

// 直接访问数组
public E get(int index) {
    rangeCheck(index);

    return elementData(index);
}

// 设置指定位置为新元素,返回旧元素
public E set(int index, E element) {
    rangeCheck(index);

    E oldValue = elementData(index);
    elementData[index] = element;
    return oldValue;
}

Remove()

// 删除指定位置的元素,返回旧值。
// 指定位置后的元素左移一位
public E remove(int index) {
    rangeCheck(index);

    modCount++;
    // 返回旧值
    E oldValue = elementData(index);
    // 需要移动的元素个数
    int numMoved = size - index - 1;
    // index 位置后的元素左移一位
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,
                         numMoved);
    elementData[--size] = null; // clear to let GC do its work

    return oldValue;
}

// 删除指定元素
public boolean remove(Object o) {
    // 在外层判断是否为空,这样不用在每次循环中进行空判断
    if (o == null) {
        for (int index = 0; index < size; index++)
            if (elementData[index] == null) {
                fastRemove(index);
                return true;
            }
    } else {
        for (int index = 0; index < size; index++)
            if (o.equals(elementData[index])) {
                fastRemove(index);
                return true;
            }
    }
    return false;
}

private void fastRemove(int index) {
    modCount++;
    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
}

// 删除两个集合的交集
public boolean removeAll(Collection<?> c) {
    Objects.requireNonNull(c);
    return batchRemove(c, false);
}

private boolean batchRemove(Collection<?> c, boolean complement) {
    final Object[] elementData = this.elementData;
    int r = 0, w = 0;
    boolean modified = false;
    try {
        for (; r < size; r++)
            if (c.contains(elementData[r]) == complement)
                elementData[w++] = elementData[r];
    } finally {
        // Preserve behavioral compatibility with AbstractCollection,
        // even if c.contains() throws.
        if (r != size) {
            System.arraycopy(elementData, r,
                             elementData, w,
                             size - r);
            w += size - r;
        }
        if (w != size) {
            // clear to let GC do its work
            for (int i = w; i < size; i++)
                elementData[i] = null;
            modCount += size - w;
            size = w;
            modified = true;
        }
    }
    return modified;
}

// 删除指定范围的元素
protected void removeRange(int fromIndex, int toIndex) {
    modCount++;
    int numMoved = size - toIndex;
    System.arraycopy(elementData, toIndex, elementData, fromIndex,
                     numMoved);

    // clear to let GC do its work
    int newSize = size - (toIndex-fromIndex);
    for (int i = newSize; i < size; i++) {
        elementData[i] = null;
    }
    size = newSize;
}

由于查找和修改直接定位到数组下标,不涉及元素挪动和数组复制所以较快 而插入删除由于要挪动元素,涉及到数组复制,操作较慢 每次添加操作还可能进行数组扩容,也会影响到性能 ArrayList的扩容机制是扩充到原来的1.5倍 用Collections.synchronizedList方法把你的ArrayList变成一个线程安全的List List synchronizedList = Collections.synchronizedList(list);

影响性能因素

  • 数组复制 (添加和删除)
  • 数组扩容 (添加)
  • 线程不安全

总结

特点:内部使用动态数组实现

  1. 可以随机访问,按照索引位置方位效率高,O(1)
  2. 除非已排序,否则按照内容查找元素效率比较低,O(N)
  3. 添加元素的效率还可以,重新分配和复制数据的开销被平摊,O(N)
  4. 插入和删除元素效率比较低,需要移动元素,O(N)