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,最后一个位置为空。因而造成线程不安全