集合框架源码学习之ArrayList

简介

  • ArrayList基于数组进行一系列的操作:查找、删除、修改等
  • 非线程安全
  • 实现Serializable、RandomAccess、Cloneable:支持序列化、快速随机访问和克隆
  • 当容量满了,会自动扩容:增加到原来的1.5倍

源码

1.构造方法

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{   //版本号
    private static final long serialVersionUID = 8683452581122892189L;

    //默认长度为10
    private static final int DEFAULT_CAPACITY = 10;
    //默认的空数组
    private static final Object[] EMPTY_ELEMENTDATA = {};
    //操作的数据
    transient Object[] elementData;
    //实际长度
    private int size;
    //初始化长度为initialCapacity的数组
    public ArrayList(int initialCapacity) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity);
        this.elementData = new Object[initialCapacity];
    }
    //默认的构造函数,将操作的数组赋值为空数组
    public ArrayList() {
        super();
        this.elementData = EMPTY_ELEMENTDATA;
    }
    //用传进来的集合初始化数组
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        size = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    }
    ......
}

2.方法

public void trimToSize() {
    modCount++;
    //将实际长度设置为当前数组的长度
    if (size < elementData.length) {
        elementData = Arrays.copyOf(elementData, size);
    }
}

    //判断是否需要扩容
public void ensureCapacity(int minCapacity) {
    int minExpand = (elementData != EMPTY_ELEMENTDATA) ? 0 : DEFAULT_CAPACITY;
    if (minCapacity > minExpand) {
        ensureExplicitCapacity(minCapacity);
    }
}
private void ensureExplicitCapacity(int minCapacity) {
    modCount++;

    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}
//最大的容量
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
//扩容
private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    int newCapacity = oldCapacity + (oldCapacity >> 1);//原长度的1.5倍
    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);
}
    //最小不能小于0,最大不能超过Integer.MAX_VALUE
private static int hugeCapacity(int minCapacity) {
    if (minCapacity < 0) // overflow
        throw new OutOfMemoryError();
    return (minCapacity > MAX_ARRAY_SIZE) ?
        Integer.MAX_VALUE :
        MAX_ARRAY_SIZE;
}

3
public int size() {//获取当前的长度
    return size;
}
//判断是否为空
public boolean isEmpty() {
    return size == 0;
}
//判断是否存在此元素
public boolean contains(Object o) {
    return indexOf(o) >= 0;
}
//搜索此元素在哪个位置(从头开始)
public int indexOf(Object o) {
    if (o == null) {//为空的话则搜寻null的元素
        for (int i = 0; i < size; i++)
            if (elementData[i]==null)
                return i;
    } else {
        for (int i = 0; i < size; i++)
            if (o.equals(elementData[i]))
                return i;//返回元素所在的位置
    }
    return -1;//找不到则返回-1
}
//搜索元素所在位置(从后面往前搜索)
public int lastIndexOf(Object o) {
    if (o == null) {//为空的话则搜寻null的元素
        for (int i = size-1; i >= 0; i--)
            if (elementData[i]==null)
                return i;
    } else {
        for (int i = size-1; i >= 0; i--)
            if (o.equals(elementData[i]))
                return i; //返回元素所在的位置
    }
    return -1; //找不到则返回-1
}
//克隆
public Object clone() {
    try {
        ArrayList<?> v = (ArrayList<?>) super.clone();//创建一个ArrayList
       //将当前的元素拷贝到新建的ArrayList
    v.elementData = Arrays.copyOf(elementData, size); 
        v.modCount = 0;
        return v;
    } catch (CloneNotSupportedException e) {
       ……
    }
}
//转成Object[]数组,这种方式不能直接整体转型
public Object[] toArray() {
    return Arrays.copyOf(elementData, size);//用拷贝的方式
}

//可以自动转型,可整体转型
public <T> T[] toArray(T[] a) {
    if (a.length < size)
        //将ArrayList中元素拷贝一份并返回
        return (T[]) Arrays.copyOf(elementData, size, a.getClass());
    //将ArrayList中的所有元素拷贝到a数组中去
    System.arraycopy(elementData, 0, a, 0, size);
    if (a.length > size)
        a[size] = null;
    return a;
}

//根据索引获取元素
public E get(int index) {
    if (index >= size)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    return (E) elementData[index];
}
    //替换元素,并将原来的元素返回
public E set(int index, E element) {
    if (index >= size)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    E oldValue = (E) elementData[index];
    elementData[index] = element;
    return oldValue;
}
    //添加元素
public boolean add(E e) {
    //先确定大小
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}
    //根据位置添加元素
public void add(int index, E element) {
    if (index > size || index < 0)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

    ensureCapacityInternal(size + 1);  //先确定大小
    System.arraycopy(elementData, index, elementData, index + 1,
                     size - index);//从要插入的位置开始复制
    elementData[index] = element;
    size++;
}
    //根据索引删除元素
public E remove(int index) {
    if (index >= size)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    modCount++;
    E oldValue = (E) elementData[index];

    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,
                         numMoved);//相当于从index后的所有元素向前移动一个位置
    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);//从index+1开始,后一个元素的覆盖前一个元素
    elementData[--size] = null; //置空
}
 //清除数组
public void clear() {
    modCount++;

    // 遍历并逐个置空
    for (int i = 0; i < size; i++)
        elementData[i] = null;
    size = 0;
}
//添加传进来的集合
public boolean addAll(Collection<? extends E> c) {
    Object[] a = c.toArray();//先转成数组
    int numNew = a.length;
    ensureCapacityInternal(size + numNew);  // 确定大小
    System.arraycopy(a, 0, elementData, size, numNew);//从最后面添加
    size += numNew;
    return numNew != 0;
}
    //从index开始添加集合
public boolean addAll(int index, Collection<? extends E> c) {
    if (index > size || index < 0)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    Object[] a = c.toArray();//先转成数组
    int numNew = a.length;
    ensureCapacityInternal(size + numNew);  // 确定大小

    int numMoved = size - index;
    if (numMoved > 0)
        System.arraycopy(elementData, index, elementData, index + numNew,
                         numMoved);//先将index后面的元素放到扩容后的最后面
    //将要添加的元素从index开始添加
    System.arraycopy(a, 0, elementData, index, numNew);    size += numNew;
    return numNew != 0;
}
//给定范围删除
protected void removeRange(int fromIndex, int toIndex) {
       if (toIndex < fromIndex) {//验证参数
        throw new IndexOutOfBoundsException("toIndex < fromIndex");
    }

    modCount++;
    int numMoved = size - toIndex;
    //将toIndex开始的元素覆盖到fromIndex的元素上
    System.arraycopy(elementData, toIndex, elementData, fromIndex,
                     numMoved);

    int newSize = size - (toIndex-fromIndex);//获取当前元素长度
    for (int i = newSize; i < size; i++) {//从newSize开始到原长度的元素置空
        elementData[i] = null;
    }
    size = newSize;
}
//删除包含在此集合中的元素
public boolean removeAll(Collection<?> c) {
    return batchRemove(c, false);
}
//删除未包含在此集合中的元素
public boolean retainAll(Collection<?> c) {
    return batchRemove(c, true);
}
private boolean batchRemove(Collection<?> c, boolean complement) {
    final Object[] elementData = this.elementData;
    int r = 0, w = 0;
    boolean modified = false;
    try {//如果complement为true先将存在的元素放到临时的数组中,用于判断是否包含
        //如果complement为false先将不存在的元素放到临时的数组中,用于删除
        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++)//将包含的都置null
                elementData[i] = null;
            modCount += size - w;
            size = w;
            modified = true;
        }
    }
    return modified;
}

总结

  • 基于数组
  • 构造函数:默认长度为10,可以传进来集合
  • 容量不足会扩大到原来的1.5倍,最小为0,最大为MAX_VALUE-8
  • System.arrayCopy:native方法,将原来的数组复制到另一个数组,可指定长度和第一个复制的位置
  • Object[] toArray()方法:不能直接整体转型。如果对数组的一个一个转型则不会抛异常
  • T[] toArray(T[] a):可以直接将获取的数组进行整体转型
  • ArrayList支持存放null值
  • 对于随机查找和效率高;对于增删效率低,因为要移动大量的元素。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值