ArrayList是基于存储元素的Object[] array来实现的,它会在内存中开辟一块连续的空间来存储。ArrayList实现了List<E>, RandomAccess, Cloneable, java.io.Serializable接口,可以看出它是List接口实现类。接下来通过几个方面来了解ArrayList的工作原理。
1.基本参数
private static final int DEFAULT_CAPACITY = 10;
/**
* Shared empty array instance used for empty instances.
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
transient Object[] elementData; // non-private to simplify nested class access
/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size;
/**
* 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;
以上是初始化的设置,其中:
DEFAULT_CAPACITY :表示默认的初始容量,默认值为10;
Object[] EMPTY_ELEMENTDATA:创建ArrayList对象时,表示初始化容量值为0;
Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA:调用无参构造函数时创建的数组,表示默认的对象。
transient Object[] elementData:表示ArrayList的引用变量,由于ArrayList实现了序列化接口,所以这里用transient修饰数组对象,表示禁止序列化该对象。
private int size:该成员变量表示Object[]数组中元素个数。
MAX_ARRAY_SIZE:表示数组最大存储容量,定义值为:Integer.MAX_VALUE - 8。
2.构造函数
ArrayList共有三个构造函数
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);
}
}
/**
* Constructs an empty list with an initial capacity of ten.
*/
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) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
1. ArrayList(int initialCapacity):该构造函数传入一个表示初始容量的参数,如果该参数小于0就报错,如果等于0就将EMPTY_ELEMENTDATA赋值给数组引用变量elementData;如果大于0,则创建一个初始容量的Object[]数组。
2.ArrayList():无参构造函数,则将前面声明的默认空数组赋值给elementData。
3.ArrayList(Collection<? extends E> c):当传入的参数是一个集合时,需要通过c.toArray()方法对其进行转化,并判断如果集合为空,则将elementData赋值为前面声明的EMPTY_ELEMENTDATA即可;否则,需要调用Arrays.copyOf(elementData, size, Object[].class),将集合元素复制给一个Object数组并且复制给elementData变量。
3.常用方法
对于ArrayList常用的方法有size()、isEmpty()、contains(Object o)、get(int index)、set(int index, E element)、add(E e)、add(int index, E element)、remove(int index)、remove(Object o)等方法。这里主要讲一下get、add、remove三类方法:
首先是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++;
}
add(E e)是在数组最后添加元素,每添加一个元素,会调用ensureCapacityInternal(size + 1)来确保数组的容量,以下是该函数的功能实现:
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(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;
}
调用ensureCapacityInternal(int minCapacity),如果该数组不为空,则会在当前函数中调用ensureExplicitCapacity(int minCapacity),在该函数继续调用grow(int minCapacity),然后在grow(int minCapacity)中进行具体处理,由上面可以知道先对其容量进行扩容,newCapacity = oldCapacity + (oldCapacity >> 1)表示容量扩成原来的1.5倍。然后通过对newCapacity与传入的minCapacity进行比较从而确定最后的新数组的容量,并将原来的元素都复制到新扩容的数组中。然后回到add方法中,之后再原来元素后面添加元素。
add(int index, E element)则是跟add(E e)一样,通过ensureCapacityInternal(int minCapacity)进行扩容,然后通过调用System.arraycopy(elementData, index, elementData, index + 1,size - index)函数来实现挪动,将index之后的元素均往后移动,然后在index下标处添加元素。
再来讲解一下remove
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
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
return oldValue;
}
/**
* Removes the first occurrence of the specified element from this list,
* if it is present. If the list does not contain the element, it is
* unchanged. More formally, removes the element with the lowest index
* <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
* (if such an element exists). Returns <tt>true</tt> if this list
* contained the specified element (or equivalently, if this list
* changed as a result of the call).
*
* @param o element to be removed from this list, if present
* @return <tt>true</tt> if this list contained the specified element
*/
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;
}
remove(int index)这表示删除index下标的元素,通过System.arraycopy(elementData, index+1, elementData, index,numMoved)方法将index后面的元素复制到从index起始的位置,然后把size-1位置清空。remove(Object o)则通过遍历元素,如果匹配了o元素,则将其删除。
最后是get(int index)
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
首先通过rangeCheck(int index)来检测index是否在容量范围之内,如果在范围之外则报错,否则返回index位置的元素。
4.总结
ArraysList会在内存中开辟一块连续的空间来存储,由于空间存储是连续的,可以利用下标来访问元素,因此查询速度较快;但是插入元素时,需要移动容器中的元素,所以对数据的插入操作执行的比较慢。ArrayList默认的初始容量是10,同时支持传入自定义的初始容量。当数据添加使得元素超过当前容量时,就会利用Arrays.copyOf()方法将元素复制到一个Object[]数组,并对其扩容,容量是当前容量的1.5倍,并且将该Object[]数组传递给原来的数组引用变量,实现扩容。