一、简介
ArrayList 是以初始容量大小为10的数组实现的,超出容量大小时通过System.arraycopy()会扩容原大小的50%的容量,如果扩容之后还不满足需求,就直接扩容为需求的大小。
ArrayList是按照数组下标访问元素 get(i)/set(i,e)的性能高,这个是数组的优势。
直接在数组的末尾加入元素add(e)的性能也高,但是如果按照下标插入、删除元素add(i,e),remove(i),remove(e),则需要通过System.arraycopy()来移动部分受影响的元素,性能也就变差了。
二、ArrayList的源码解读
ArrayLis的构造方法
/**
* 带初始容量的构造
*/
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);
}
}
/**
*无参构造
*/
public ArrayList() {
//使用默认的空数组
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public ArrayList(Collection<? extends E> c) {
Object[] a = c.toArray();
if ((size = a.length) != 0) {
if (c.getClass() == ArrayList.class) {
elementData = a;
} else {
elementData = Arrays.copyOf(a, size, Object[].class);
}
} else {
// replace with empty array.
elementData = EMPTY_ELEMENTDATA;
}
}
2.1 添加元素-add(E,e)
public boolean add(E e) {
//此处就是数组扩容的关键代码
ensureCapacityInternal(size + 1); // Increments modCount!!
//将元素按照下表自增添加到数组中去
elementData[size++] = e;
return true;
}
数组的扩容就是通过这个方法去扩容的ensureCapacityInternal()下面我门看此处方法:
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
//获取到所需容量,然后去扩容
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// 此处是判断数组是否需要去扩容
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
//将容量扩容到原容量的1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
//如果扩容1.5倍的大小之后还还不满足需求,就直接扩为需求的大小
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
//容量到大小也不是无限制的,最大到容量就是Integer的最大值
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
//通过数组拷贝扩展数组大小
elementData = Arrays.copyOf(elementData, newCapacity);
}
2.2 set和get函数
ArrayList的set和get函数,比较简单,先做index的检查然后执行相关的赋值。
public E set(int index, E element) {
//下标越界检查
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
E oldValue = (E) elementData[index];
//下标为index的位置赋值
elementData[index] = element;
return oldValue;
}
public E get(int index) {
//越界检查
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
return (E) elementData[index];
}
2.3 remove方法
/**根据数组下标删除*/
public E remove(int index) {
//越界检查
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
modCount++;
E oldValue = (E) elementData[index];
//移动个数
int numMoved = size - index - 1;
if (numMoved > 0)
//若果移动的个数大于0,说明该index不是末尾位置,需要进行数组的拷贝
System.arraycopy(elementData, index+1, elementData, index, numMoved);
elementData[--size] = null; // clear to 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 remove method that skips bounds checking and does not
* return the value removed.
*/
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; // clear to let GC do its work
}
总结
ArrayList在使用过程中,最好根据业务的大小提前定义好容量的大小,避免数组扩容导致性能和效率低下。并且在使用的过程中需要注意线程的安全,避免多线程操作集合。