ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
- 类变量&常量
static final int DEFAULT_CAPACITY=10 默认的初始容量
static final Object[] EMPTY_ELEMENTDATA = {} 空集,用于空的实例。
static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}
空集,用于空的实例。二者区别在于当地一个元素被添加时,可以知道已改膨胀多少
transient Object[] elementData
Array的buffer,当添加元素时即添加到这里
int size:ArrayList的size,即elementData里面的元素个数
modMount = 0 :AbstranctList类的变量,记录操作数。
2.构造函数
new ArrayList() : this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
new ArrayList(int initialCapacity) : this.elementData = new Object[initialCapacity]
new ArrayList(Collection<? extends E> c) :
this.elementData = c.toArray();
size = elementData.length;
if(size!=0){
if(elementData.getClass() != Object[].class){
elementData = Arrays.copyOf(elementData,size,Object[].class);
}
}
3.内部类
Itr implements Iterator : 对ArrayList进行遍历
ListItr extends Itr implements ListIterator<E> : 对ArrayList进行遍历,可以向前遍历
SubList extends AbstractList<E> implements RandomAccess :ArrayList的子类,可以从任意位置得到
4.重要函数
1. public boolean add(E e): 添加一个元素
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
protected void ensureCapacityInternal(int minCapacity) {//扩容函数。
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) 第一个构造函数,且elelementData为空
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++; //操作数+1
// 考虑溢出
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
//数组最大的分配容量,有些虚拟机可能会保留一些header信息,如果过大的话会导致OOM(大于vm限制)
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private void grow(int minCapacity) { //扩容核心函数
// 考虑溢出
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();
//判断minCapacity是否大于MAX_ARRAY_SIZE
//由grow函数可知,若newCapacity<minCapacity,则newCapacity = minCapacity,所以
//newCapacity必定大于MAX_ARRAY_SIZE;若newCapacity>minCapacity,则再判断minCapacity
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
2. 最小化ArrayList的存储空间,即让elementData.length = size,因为之前有扩容,故二者不相同
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
3.指定位置添加元素
public void add(int index, E element) {
rangeCheckForAdd(index); //检查是否越界(与size判断)
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index); //使用System.arrayCopy
elementData[index] = element;
size++;
}
4.返回指定位置的元素,若为null,则返回第一个null的位置
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
5.返回ArrayList中元素的个数
public int size() {
return size;
}
6.可以自定义扩容大小,传入参数为扩容后的容量
public void ensureCapacity(int minCapacity) {
int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
// any size if not default element table
? 0
: DEFAULT_CAPACITY;
if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
}
7.克隆函数
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone(); //使用Object的protect函数clone()
v.elementData = Arrays.copyOf(elementData, size); //使用size作为容量,原来扩容的部分不在
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
}
8. 变成Array数组形式
public Object[] toArray() { //Object[] 类型
return Arrays.copyOf(elementData, size);
}
//将值复制到数组a中
public <T> T[] toArray(T[] a) {
if (a.length < size)
// 创建一个新的数组,使用a的class类型
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
//a的长度大于size,那么将elementData全部复制,size赋值为null(只一次)
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
9.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[index]=elementData[index+1]
elementData[--size] = null; // clear to let GC do its work
return oldValue; //一般set或者remove(int index)函数均返回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;
}
// 用于按元素删除,与按位置删除函数的区别在于不用检查边界条件和返回oldValue
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
}
10.retainAll 仅保留在该列表中包含的所述元素指定的集合。换句话说,从该列表中删除所有未包含在指定集合中的元素。
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
//complement: 判断是在容器中还是不在容器中的元素进行保留
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < size; r++)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// 在try中若抛出异常,则执行该段if语句
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++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
11.清除list
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null; //全部赋值为null,让gc自动清理
size = 0;
}