ArrayList分析

ArrayList继承AbstractList,实现List<E>, RandomAccess, Cloneable, java.io.Serializable

其中实现的Cloneable接口,重写了clone方法

/**
     * Returns a shallow copy of this <tt>ArrayList</tt> instance.  (The
     * elements themselves are not copied.)
     *
     * @return a clone of this <tt>ArrayList</tt> instance
     */
    public Object clone() {
        try {
            ArrayList<?> v = (ArrayList<?>) 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(e);
        }
    }

从上面的源码可知,ArrayList中的clone方法是一种浅拷贝,拷贝的其中的引用,这在使用的过程中需要注意。

同时ArrayList也是实现了Serializable接口,所以可以通过序列化和反序列化的方式对对象进行深拷贝。

RandomAccess接口是空接口,里面没有任务方法,其作用主要是用于标记作用,实现该接口的类表示可以快速随机访问,也就是通过下标。如果没有实现此接口在访问时可以考虑使用迭代访问,在数据量很大时,这两种不同的方式耗时差距也比较明显。

现在探讨ArrayList是否是线程安全的?

首先查看add()方法的实现:

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

    /**
     * Inserts the specified element at the specified position in this
     * list. Shifts the element currently at that position (if any) and
     * any subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    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++;
    }

ArrayList定义了两个添加元素的方法,前者是默认的列表的末尾添加元素,后者是在制定的位置添加元素。ensureCapacityInternal()用于判断ArrayList是否需要扩容。

看一下扩容的方法:

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

可以知道扩容是按照1.5倍增加的,然后在使用Arrays.copyOf方法复制数组的值。

查看public void add(int index, E element)(){}方法,这里需要将index及其以后的元素往后一个位置,空出index位置的值,所以可以看出ArrayList如果频繁的添加元素会很耗时。

分析完add方法的实现后,接着看一下线程安全方面的问题:

add()方法执行时,假设有两个线程A和B同时进行添加元素,A和B都获取到size的值为5,A线程进行添加元素后size++,size大小变为6,然后B线程在进行添加元素,但是B获取到的size的值也是5,所以B线程会在下表为的5的位置添加元素,所以B线程操作会覆盖A线程操作的结果。size变为6,最后一个位置为空。因而造成线程不安全

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值