Java源代码走读--ArrayList

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    private static final long serialVersionUID = 8683452581122892189L;//由于实现了序列化接口,定义一个UID能够保证数据持久化写入和读取
<span style="white-space:pre">	</span>//如果没有serialVersionUID可能导致输入持久化以后,对代码进行了修改,这时jdk会生成一个新的UID,是原来写入的数据恢复不出来了
    /**
     * 元素存储到Object对象数组当中
     */
    private transient Object[] elementData;

    /**
     * 元素个数
     */
    private int size;

    /**
     * 根据初始化容量构造ArrayList
     */
    public ArrayList(int initialCapacity) {
	super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
	this.elementData = new Object[initialCapacity];
    }

    /**
     * ArrayList默认构造函数初始化容量为10
     */
    public ArrayList() {
	this(10);
    }

    /**
     * 使用其他容器类来初始化ArrayList
     */
    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);
    }

    /**
     * <span style="font-family: Arial, Helvetica, sans-serif;">将ArrayList的大小变为当前存储元素的个数</span>
     */
    public void trimToSize() {
	modCount++;
	int oldCapacity = elementData.length;
	if (size < oldCapacity) {
            elementData = Arrays.copyOf(elementData, size);
	}
    }

    /**
     * 增加ArrayList的容量,新容量根据minCapacity的大小来定
     * 如果传入的minCapacity的大小比原容量的1.5倍+1大,那么就将新容量定位minCapacity
     * 否则为原容量的1.5倍+1,并将原ArrayList拷贝到新的空间当中.
     *
     */
    public void ensureCapacity(int minCapacity) {
	modCount++;
	int oldCapacity = elementData.length;
	if (minCapacity > oldCapacity) {
	    Object oldData[] = elementData;
	    int newCapacity = (oldCapacity * 3)/2 + 1;
    	    if (newCapacity < minCapacity)
		newCapacity = minCapacity;
            // minCapacity is usually close to size, so this is a win:
            elementData = Arrays.copyOf(elementData, newCapacity);
	}
    }

    /**
     * 返回ArrayList当中存储元素的个数
     */
    public int size() {
	return size;
    }

    /**
     * 是否为空
     */
    public boolean isEmpty() {
	return size == 0;
    }

    /**
     * 是否包含某个元素
     */
    public boolean contains(Object o) {
	return indexOf(o) >= 0;
    }

    /**
     * 返回查找对象的下标,找到返回下标,未找到返回-1
     * ArrayList当中是可以存null的,原理跟对象数组相同,即引用为空
     */
    public int indexOf(Object o) {
	if (o == 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;
    }

    /**
     * 返回查找对象在ArrayList中最后一次出现位置的下标,找到返回下标,未找到返回-1,从后向前找
     */
    public int lastIndexOf(Object o) {
	if (o == 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;
    }

    /**
     * 返回ArrayList的浅拷贝(元素背身并没有被拷贝)
     */
    public Object clone() {
	try {
	    ArrayList<E> v = (ArrayList<E>) super.clone();
	    v.elementData = Arrays.copyOf(elementData, size);
	    v.modCount = 0;
	    return v;
	} catch (CloneNotSupportedException e) {
	    // this shouldn't happen, since we are Cloneable
	    throw new InternalError();
	}
    }

    /**
     * 返回包含ArrayList当中所有元素的一个数组
     * 这个数组是新数组,可以随意进行操作而不影响原ArrayList当中的元素
     * 同时也是array和集合类操作的桥梁
     */
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    /**
     * 返回给定类型的数组
     */
    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
	System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }

    // Positional Access Operations

    /**
     * 返回特定下标的元素
     */
    public E get(int index) {
	RangeCheck(index);//先检查是否越界

	return (E) elementData[index];
    }

    /**
     * 修改特定位置的元素值,返回修改前的值
     */
    public E set(int index, E element) {
	RangeCheck(index);

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

    /**
     * 向ArrayList末尾添加元素
     */
    public boolean add(E e) {
	ensureCapacity(size + 1);  // Increments modCount!!
	elementData[size++] = e;
	return true;
    }

    /**
     * 将元素添加到加入到给定下标位置处
     */
    public void add(int index, E element) {
	if (index > size || index < 0)
	    throw new IndexOutOfBoundsException(
		"Index: "+index+", Size: "+size);

	ensureCapacity(size+1);  // Increments modCount!!
	System.arraycopy(elementData, index, elementData, index + 1,
			 size - index);
	elementData[index] = element;
	size++;
    }

    /**
     * 删除给定下标处的元素,返回删除的元素
     */
    public E remove(int index) {
	RangeCheck(index);

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

	int numMoved = size - index - 1;
	if (numMoved > 0)
	    System.arraycopy(elementData, index+1, elementData, index,
			     numMoved);
	elementData[--size] = null; // 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; // Let gc do its work
    }

    /**
     * 删除list当中的所有元素,清空list
     */
    public void clear() {
	modCount++;

	// Let gc do its work
	for (int i = 0; i < size; i++)
	    elementData[i] = null;

	size = 0;
    }

    /**
     * 将另一个集合类型当中的所有元素添加到ArrayList之后
     */
    public boolean addAll(Collection<? extends E> c) {
	Object[] a = c.toArray();
        int numNew = a.length;
	ensureCapacity(size + numNew);  // Increments modCount
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
	return numNew != 0;
    }

    /**
     * 将另一个集合类当中的所有元素添加到index索引位置之后
     * 当中用到了两次arraycope方法。
     */
    public boolean addAll(int index, Collection<? extends E> c) {
	if (index > size || index < 0)
	    throw new IndexOutOfBoundsException(
		"Index: " + index + ", Size: " + size);

	Object[] a = c.toArray();
	int numNew = a.length;
	ensureCapacity(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;
    }

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

	// Let gc do its work
	int newSize = size - (toIndex-fromIndex);
	while (size != newSize)
	    elementData[--size] = null;
    }

    /**
     * 查看一个下标是否越界
     */
    private void RangeCheck(int index) {
	if (index >= size)
	    throw new IndexOutOfBoundsException(
		"Index: "+index+", Size: "+size);
    }

    /**
     * 写序列化
     */
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
	// Write out element count, and any hidden stuff
	int expectedModCount = modCount;
	s.defaultWriteObject();

        // Write out array length
        s.writeInt(elementData.length);

	// Write out all elements in the proper order.
	for (int i=0; i<size; i++)
            s.writeObject(elementData[i]);

	if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }

    }

    /**
     * 读序列化
     */
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
	// Read in size, and any hidden stuff
	s.defaultReadObject();

        // Read in array length and allocate array
        int arrayLength = s.readInt();
        Object[] a = elementData = new Object[arrayLength];

	// Read in all elements in the proper order.
	for (int i=0; i<size; i++)
            a[i] = s.readObject();
    }
}

Java的ArrayList底层实际上是使用数组来实现的,较传统的数组优点是容量可以动态增长。

ArrayList对于元素的随机访问效率非常高。

默认初始化容量为10,随着不断元素的添加,容量会随之增长,增长的后的大小为原容量的1.5倍+1。

若不断的添加元素,可能会频繁的创建新数组拷贝新数组的工作,因此在使用ArrayList最好能预测需要多大空间,然后初始化,这样可以提高ArrayList的效率。

通过源代码可以看到ArrayList做的最多的就是数组的拷贝和移动操作。

arraycopy方法将原数组当中的元素拷贝到另外一个数组当中。

如果原数组和目标数组相同,则将需要拷贝的元素拷贝到一个临时数组,然后再从临时数组将元素拷贝到原数组当中。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值