因为最近正在绘制JAVA体系的脑图,在整理集合部分的时候只知道是怎么用的,但是不知道是怎么实现的,所以打算花点时间把集合部分的源码看一下,这篇博客是看完ArrayList的源码之后的一些感想。
首先,ArrayList是通过数组来实现的。因为ArrayList的元素是可以动态增加的,而且元素数量是不一定的,因此ArrayList通过在需要时进行数组的拷贝,将旧数组中元素拷贝到容量扩大后的新数组中来满足这一特性。每当插入1(add)或n(addAll)条记录时,都会将ArrayList的size(也就是数组中已经有的元素)加上1或n之后跟数组的长度进行比较,来判断数组是否能满足对新元素的存储,如果不能满足,则将数组长度扩展为之前长度的3/2(即增加原先长度的一半),如果扩展之后还不能满足需求,则将长度设置为size加1或n。源码如下:
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
/**
* The maximum size of array to allocate.
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
* 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);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
从源码中可以看出,每次进行扩展的时候都通过Arrays.copy进行数组拷贝,这个操作是需要时间的。因此如果我们可以预估到ArrayList中将要存储的元素的个数,我们可以调用ensureCapacity(int minCapacity)方法或者在初始化Arraylist的时传入容量大小来指定数组的容量,以减少数组拷贝的次数,从而带来性能上的提升。
/**
* Increases the capacity of this <tt>ArrayList</tt> instance, if
* necessary, to ensure that it can hold at least the number of elements
* specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
public void ensureCapacity(int minCapacity) {
int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
// any size if not default element table
? 0
// larger than default for default empty table. It's already
// supposed to be at default size.
: DEFAULT_CAPACITY;
if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
}
/**
* 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) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
另外,因为是预先给出了数组作为元素的容器,而且每次扩展的时候都是增加了原先的一半,这就会造成数组中没有完全填充。可以通过trimToSize()方法,将数组的长度调整为元素的个数相同,以减少空间的利用。
/**
* Trims the capacity of this <tt>ArrayList</tt> instance to be the
* list's current size. An application can use this operation to minimize
* the storage of an <tt>ArrayList</tt> instance.
*/
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}