特性:
1、ArrayList是List接口的可变数组的实现
2、实现了所有可选列表操作,并允许包括null在内的所有元素
3、除了实现List接口外,此类还提供了一些方法来操作内部用来存储列表的数组的大小
4、每个ArrayList都有一个容量,该容量是指用来存储列表元素的数组的大小
5、它总是至少等于列表的大小
6、随着向ArrayList中不断添加元素,其容量也自动增加
7、自动增长会带来数据向新数组的重新拷贝,因此,如果可预知数据量的多少,可在构造ArrayList时指定其容量
8、实现了Serializable接口,因此支持序列化,能够通过序列化传输
9、实现了RandomAccess接口,支持快速随机访问,
10、实现了Cloneable接口,能被克隆
tips:ArrayList不是线程安全的,只能用在单线程环境下,多线程环境下可以考虑用Collections.synchronizedList(List l)函数返回一个函数安全的ArrayList类,也可以使用concurrent并发包下的CopyOnWriteArrayList类。
源码分析:
(1)底层使用数组
transient Object[] elementData; // non-private to simplify nested class access
transient:是java的关键字,用来表示一个域不是该对象串行化的一部分。当一个对象被串行化的时候,transient型变量的值不包括在串行化的表示中,然而非transient型的变量是被包括进去的。
(2)构造方法
Java提供了3个构造函数
//构造一个指定初始容量的空列表
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);
}
}
//共享的空数组
private static final Object[] EMPTY_ELEMENTDATA = {};
//构造一个默认初始容量为10的空列表
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
//构造一个包含指定Collection的元素的列表,这些元按照Collection的迭代器返回他们的顺序排列的
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;
}
}
(3)存储数据
总共提供了5中存储数据的方法:
第一种:更换
/**
* 使用给定的值替换特定位置的值
*
* @param index 需要替换的位置
* @param element 替换的值
* @return 该位置的之前的值
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E set(int index, E element) {
rangeCheck(index); //检测index是否在数组大小范围内
E oldValue = elementData(index);//返回数组index位置的值
elementData[index] = element; //将index位置的值赋值为传入的值
return oldValue;
}
//检测index是否在数组范围内,如果不在就抛出异常
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
//返回index位置elementData数组的值
E elementData(int index) {
return (E) elementData[index];
}
第二种:添加元素
//添加元素到数组的最后位置
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { //如果初始化为空
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); //就设置数组大小为10
}
ensureExplicitCapacity(minCapacity);
}
默认初始化大小
private static final int DEFAULT_CAPACITY = 10;
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); //获取新的数组的长度=1.5*旧的数组长度
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; //如果最小需求长度大于最大范围,就返回Integer的最大值;否则返回最大范围
}
第三种:元素插入到指定位置
/**
* 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++;
}
第四种:添加集合
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray(); //将集合转换成数组
int numNew = a.length; //新的集合的长度
ensureCapacityInternal(size + numNew); // Increments modCount
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
第五种:添加集合到指定位置
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;
}
(4)读取数据
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
(5)删除
第一种:删除指定位置的元素
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;
}
第二种:删除第一次出现的特定元素
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++) //遍历查找是否有位置的值为null
if (elementData[index] == null) {
fastRemove(index); //快速删除index位置的值
return true;
}
} else {
for (int index = 0; index < size; index++) //遍历查找是否有元素的值和给定的元素相同
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1; //
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved); //将index后面的元素全部前移一位,覆盖index位置的值
elementData[--size] = null; // clear to let GC do its work
}
第三种:删除一个集合中的所有元素
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c); //Object中的方法,用于判断元素非空
return batchRemove(c, false);
}
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData; //将原有的数组赋值给新的数组
int r = 0, w = 0;
boolean modified = false;
try {
//功能是将未出现在集合c中的元素放到数组的前端,从第一个开始放
for (; r < size; r++)
if (c.contains(elementData[r]) == complement) //查找集合c的是否包含数组中的元素
elementData[w++] = elementData[r];//不包含,就将r位置的元素放到数组的前部位置
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r); //复制数组
w += size - r;
}
if (w != size) {
// clear to let GC do its work
for (int i = w; i < size; i++) //设置后面的元素为null,方便GC回收
elementData[i] = null;
modCount += size - w; //记录修改次数
size = w;
modified = true;
}
}
return modified;
}
/*
* 将src数组的srcPos位置的元素复制到dest数组的destPos位置,复制长度为length,
* 使用的是JNI,调用c的方法,这样可以加快速度
* @param src the source array.
* @param srcPos starting position in the source array.
* @param dest the destination array.
* @param destPos starting position in the destination data.
* @param length the number of array elements to be copied.
* @exception IndexOutOfBoundsException if copying would cause
* access of data outside array bounds.
* @exception ArrayStoreException if an element in the <code>src</code>
* array could not be stored into the <code>dest</code> array
* because of a type mismatch.
* @exception NullPointerException if either <code>src</code> or
* <code>dest</code> is <code>null</code>.
*/
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);