可以介绍一下 ArrayList内部是如何实现数组的增加和删除的,因为数组在创建时长度是固定的,那么就有个问题我们往ArrayList中不断的添加对象,它是如何管理这些数组呢?
对于ArrayList,相信大家都很熟悉,在开发中比较常用的集合。先总体介绍一下ArryList的实现。
1.基于数组实现,是一个动态数组,其容量能自动增长。
2.ArrayList不是线程安全的,建议在单线程中使用,多线程可以选择Vector或CopyOnWriteArrayList。
3.实现了RandomAccess接口,可以通过下标序号进行快速访问。
4.实现了Cloneable接口,能被克隆。
5.实现了Serializable接口,支持序列化。
ArrayList源码解析
ArrayList继承了AbstractList并实现了List,RandomAccess, Cloneable, java.io.Serializable 接口,上面做了相应的介绍就不再阐述了。关键我们看两个重要的属性elementData和size。
/**
* The array buffer into which the elements of the ArrayList are stored.(ArrayList的元素的数组缓冲区存储)
* The capacity of the ArrayList is the length of this array buffer(ArrayList的容量是这个数组的长度缓冲区). Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData;
elementData:保存了添加到ArrayList中的元素。实际上,elementData个动态数组,我们能通过构造函数ArrayList(intinitialCapacity)来执行它的初始容量为initialCapacity;如果通过不含参数的构造函数ArrayList()来创建ArrayList,则elementData的容量默认是10。
//The size of the ArrayList
size: 动态数组的实际大小。
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
private static final long serialVersionUID = 8683452581122892189L;
private static final int DEFAULT_CAPACITY = 10;
private static final Object[] EMPTY_ELEMENTDATA = {};
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
transient Object[] elementData; // non-private to simplify nested class access
private int size;
//带容量大小的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);
}
}
// ArrayList无参构造函数。默认容量是10。
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
elementData数组的大小会根据ArrayList容量的增长而动态的增长,具体的增长方式,ensureCapacity()函数很清楚。
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);
}
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
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;
}
返回元素在列表中的位置 Returns the element at the specified position in this list.
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
向集合中添加元素
//Appends the specified element to the end of this list.
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
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++;
}
//Inserts all of the elements in the specified collection into this
* list, starting at the specified position.
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index);
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount
int numMoved = size - index;
if (numMoved > 0)
System.arraycopy(elementData, index, elementData, index + numNew,
numMoved);
System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}
ArrayList 内部是用Object[]实现的。接下来我们分别分析ArrayList的构造、add、remove、clear 方法的实现原理。
总结
1.ArrayList 实际上是通过一个数组去保存数据的。当我们使用无参构造函数构造ArrayList时,则ArrayList的默认容量大小是10。
2.当ArrayList容量不足以容纳全部元素时,ArrayList会重新设置容量:新的容量=“(原始容量x3)/2 + 1”;
3.如果设置后的新容量还不够,则直接把新容量设置为传入的参数。
4.ArrayList查找效率高,插入删除元素的效率低。
5.ArrayList的克隆函数,即是将全部元素克隆到一个数组中。
6.ArrayList实现java.io.Serializable的方式。当写入到输出流时,先写入“容量”,再依次写入“每一个元素”;当读出输入流时,先读取“容量”,再依次读取“每一个元素”。