Java容器来一发(二)ArrayList

1、ArrayList代码阅读

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    private transient Object[] elementData;

    /**
     * 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
     */
    public ArrayList(int initialCapacity) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
    }

    /**
     * Returns the element at the specified position in this list.
     *
     * @param  index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E get(int index) {
        rangeCheck(index);

        return elementData(index);
    }

    /**
     * Replaces the element at the specified position in this list with
     * the specified element.
     *
     * @param index index of the element to replace
     * @param element element to be stored at the specified position
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E set(int index, E element) {
        rangeCheck(index);

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

1)ArrayList实现了随机访问接口RandomAccess,这表示可以提供较好的随机访问性能(可通过instanceof判断是否实现某种接口)。

2)ArrayList实现了可复制接口Cloneable,这意味着ArrayList可以合法地调用clone()方法进行复制(否则会报异常)。这里补充下对象拷贝的类型,对象拷贝分为浅拷贝和深拷贝,浅拷贝是指在拷贝对象时,对于基本数据类型的变量会重新复制一份,而对于引用类型的变量只是对引用进行拷贝,没有对引用指向的对象进行拷贝。而深拷贝是指在拷贝对象时,同时会对引用指向的对象进行拷贝。区别就在于是否对对象中的引用变量所指向的对象进行拷贝。

3)ArrayList实现序列化接口Serializable,把对象转换为字节序列的过程称为对象的序列化,可序列化的意义在于,如果不按序列化的策略,有对象的引用时会有问题,如果A的对象a中引用了B的对象b,那么会将a的数据复制到b中,如果改了a的数据,就要将a的数据复制到每一份copy中。

我们注意到private变量elementData前面加了transient关键字,它的意义在于被修饰的属性在序列化时,不会序列化到指定目的地中。

猜你喜欢

转载自blog.csdn.net/ss1300460973/article/details/85551700