ArrayList实现了AbstractList类,继承了List\RandonAccess(能够提供快速\随即访问)\Cloneable(可以生成field-for-field实例副本)\Seri...(可序列化)接口
1.主要的属性
/**
* list的初始长度
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* list以数组作为缓冲区,且底层存储结构是数组
*/
transient Object[] elementData;
/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size;
/**
* 默认大小的空实例的共享数组实例,主要用于比较添加一个元素的膨胀程度
* 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 = {};
/**
* 要分配的最大长度(list实际的最大长度为Interger.MAX_VALUE:21亿多)
* OutOfMemoryError: Requested array size exceeds VM limit
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
2.主要构造方法
// 入参list的长度
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
// 默认占用intial 个 位置
this.elementData = new Object[initialCapacity];
// 入参为0,则默认空数组
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
// 无参构建方法。默认长度为10,数组实例是空数组
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
// 入参是list对象,相当于copy一个新数组对象 (例如List<String> v = new ArrayList<>(list))
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.主要方法(内部方法)
1.扩容方法(一般在add的时候用到)
// 确保长度足够,否则扩容
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
// 计算长度
private static int calculateCapacity(Object[] elementData, int minCapacity) {
// 如果为空数组,则比较入参长度 跟 默认list的长度10 取最大返回
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
// 确保长度
private void ensureExplicitCapacity(int minCapacity) {
// 扩容一次 modCount++
modCount++;
// 防止元素溢出,进行扩容
if (minCapacity - elementData.length > 0)
//扩容方法
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
// 初始扩容长度为0.5倍。例如原长度为10,则 新长度=10 + 10》1 = 15;
int newCapacity = oldCapacity + (oldCapacity >> 1);
// 初始扩容长度不足时,则默认入参的长度
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
// 当扩容后的长度大于了最大长度 (Inter.MAX_VALUE - 8)
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();
// 如果当前入参长度大于了VM分配的最大长度(MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8)
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
4.主要方法(实际用到的)
/**返回数组长度
* @return the number of elements in this list
*/
public int size() {
return size;
}
/**
* 数组是否为空
* @return <tt>true</tt> if this list contains no elements
*/
public boolean isEmpty() {
return size == 0;
}
// 数组是否包含某个元素
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
// 查找元素所在的下标
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;
}
// 深拷贝
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
}
// 添加元素
public boolean add(E e) {
// 确保长度足够
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
// get方法返回元素
public E get(int index) {
// 校验下标是否越界
rangeCheck(index);
// 数组
return elementData(index);
}
// set方法赋值元素,返回旧值
public E set(int index, E element) {
// 校验下标
rangeCheck(index);
// 新值替换旧值,旧值返回
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
// 根据下标移除,尽量使用迭代器移除
public E remove(int index) {
rangeCheck(index);
// 移除一次就modCount++;用来校验当前操作跟原来的操作是否一致,否则异常
modCount++;
E oldValue = elementData(index);
// 新数组的长度
int numMoved = size - index - 1;
if (numMoved > 0)
// 本地方法arraycopy
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) {。。。}
// 代码中的临时数组,用完可以clear,方便GC
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
// 将一个数组添加到新数组中
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;
}
// 移除指定范围的元素
protected void removeRange(int fromIndex, int toIndex) {...}
// 仅保留此列表中包含在指定集合中的元素。换句话说,从这个列表中删除所有不包含在指定集合中的元素。
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
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 {
// 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++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
boolean removeIf(Predicate<? super E> filter){...}