关系图
可以看到,ArrayList继承了AbstractList,而AbstactList有继承了AbstractCollection,实现了list。并且ArrayList实现了Cloneable支持对象的克隆,也实现serializable支持序列化。
内置属性:
private static final long serialVersionUID = 8683452581122892189L;
/**
* 初始化容量
*/
private static final int DEFAULT_CAPACITY = 10;
/**
*用于空实例的共享空数组实例。
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
*用于默认大小的空实例的共享空数组实例。我们将此与EMPTY_ELEMENTDATA区分开来,以便在添加第一个元素时知道要膨胀多少。
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
*用来缓存数组中的元素的数组,该数组的长度即为ArrayList的容量
*添加第一个元素时,任何elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA的空ArrayList都将扩展到默认容量。elementData.length表示数组的大小,不一定是元素的个数
*/
transient Object[] elementData; // non-private to simplify nested class access
/**
* 数组大小,既包含元素的个数
*
* @serial
*/
private int size;
由他的内置属性,我们可以看到ArrayList的底层实际上是一个数组,而对于默认容量下数组为空和数组为空又分别用两个数组进行区分。这样是为了在扩容时确定数组的原始容量。
构造函数
/**
* 构建一个特定容量的空列表
*/
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {//大于0直接创建相应大小的数组
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {//等于0赋为空数组
this.elementData = EMPTY_ELEMENTDATA;
} else {//数值违法抛出异常
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
/**
*创建一个容量为10的空数组
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
* 构造一个包含特定元素集合的列表, 他们能够通过集合的迭代器按顺序返回
*/
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
//
this.elementData = EMPTY_ELEMENTDATA;
}
}
在创建包含特定集合的列表时,先判断元素个数是否为0,如果为0则设为空的对象数组,若不为0则通过copyOf方法进行元素复制。
方法
调整容量为实际大小- trimToSize
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
若数组的长度大于实际容量,则将数组中的元素复制到长度为size的数组中。
将数组扩容为指定容量-ensureCapacity
public void ensureCapacity(int minCapacity) {
int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
? 0
: DEFAULT_CAPACITY;//为默认容量设为默认容量
if (minCapacity > minExpand) {//指定容量大于最小容量
ensureExplicitCapacity(minCapacity);
}
}
/**
*确定指定的容量下是否需要扩容
**/
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)//指定容量大于数组的大小
grow(minCapacity);
}
/**
*要分配的最大数组大小。
一些VM在阵列中保留一些对象头。尝试分配更大的数组可能会导致OutOfMemoryError:请求的数组大小超过VM限制
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
*增加容量以确保它至少可以容纳由minimum capacity参数指定的元素数。
*/
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);//扩容1/2
if (newCapacity - minCapacity < 0)//若新容量小于指定容量,则赋为指定容量
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)//新的容量超过最大值,将其设为最大容量
newCapacity = hugeCapacity(minCapacity);
//新容量>=指定容量,则进行复制:
elementData = Arrays.copyOf(elementData, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // 指定容量小于0,则内存溢出
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
lastIndexOf与此相反,为倒序遍历。
返回指定位置元素下标- indexOf
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;
}
列表克隆-clone
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();//先克隆对象
v.elementData = Arrays.copyOf(elementData, size);//复制元素
v.modCount = 0;//默认修改数为0
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
}
返回列表中的元素 -toArray
/**
*调用copyOf方法转换成数组
*/
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
/**
* 将列表按照相应的数组的运行时类型转换
*/
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
if (a.length < size)//数组长度小于列表大小,赋值列表
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);//大于等于列表长度直接复制
if (a.length > size)
a[size] = null;
return a;
}
获取设置元素-get、set
@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));
}
public E set(int index, E element) {
rangeCheck(index);//范围检查
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
元素添加-add
/**
*确定数组是否需要扩容为默认容量与size+1的最大值
**/
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {//数组是否为默认容量数组
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
public boolean add(E e) {
ensureCapacityInternal(size + 1); //确定是否需要扩容,将数组大小设为默认容量与size+1的最大值
elementData[size++] = e;
return true;
}
public void add(int index, E element) {
rangeCheckForAdd(index);//范围检查
ensureCapacityInternal(size + 1); //确定是否需要扩容
System.arraycopy(elementData, index, elementData, index + 1,
size - index);//数组复制
elementData[index] = element;
size++;
}
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
//
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;
}
元素删除-remove
//删除特定位置
public E remove(int index) {
rangeCheck(index);//范围检查
modCount++;//修改数+1
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;
}
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
}
//删除值
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;
}
删除所有元素-removeAll
//从此列表中删除指定集合中包含的所有元素。
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
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 {
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) {//元素减少,则将剩余位置补为null
// 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;
}
遍历列表-foreach
public void forEach(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int expectedModCount = modCount;//记录当前修改值
@SuppressWarnings("unchecked")
final E[] elementData = (E[]) this.elementData;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
action.accept(elementData[i]);
}
if (modCount != expectedModCount) {//如果遍历时修改值发生变化
throw new ConcurrentModificationException();
}
}
迭代器
方法
public ListIterator<E> listIterator() {
return new ListItr(0);
}
迭代类
private class ListItr extends Itr implements ListIterator<E> {
ListItr(int index) {
super();
cursor = index;//游标设为index
}
public boolean hasPrevious() {
return cursor != 0;
}
public int nextIndex() {
return cursor;
}
public int previousIndex() {
return cursor - 1;
}
@SuppressWarnings("unchecked")
public E previous() {//返回前一个元素
checkForComodification();//检查是否被修改
int i = cursor - 1;//游标-1
if (i < 0)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i;
return (E) elementData[lastRet = i];
}
public void set(E e) {//设置当前值
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.set(lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void add(E e) {//添加值
checkForComodification();
try {
int i = cursor;
ArrayList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
对象序列化
/**
*将列表序列化
**/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
// Write out element count, and any hidden stuff
int expectedModCount = modCount;
s.defaultWriteObject();
// Write out size as capacity for behavioural compatibility with clone()
s.writeInt(size);
// Write out all elements in the proper order.
for (int i=0; i<size; i++) {
s.writeObject(elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
/**
* 将列表反序列化
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
elementData = EMPTY_ELEMENTDATA;
// Read in size, and any hidden stuff
s.defaultReadObject();
// Read in capacity
s.readInt(); // ignored
if (size > 0) {
// be like clone(), allocate array based upon size not capacity
ensureCapacityInternal(size);
Object[] a = elementData;
// Read in all elements in the proper order.
for (int i=0; i<size; i++) {
a[i] = s.readObject();
}
}
}
问题:
1. modCount的作用?
2.为什么没有显示创建指定容量大小的数组?
----------------------------------------------------睡觉了,明天更--------------------------------------------
问题1:modCount作为list的修改计数器,每次对列表的更新都会使modCount+1,这样做完全是为了支持快速失败机制,使用迭代器进行操作时,每次操作都会进行一次checkForComodification,所以当一个线程使用迭代器时,另一个线程对列表进行修改便会抛出异常。
问题2:没有初始化的时候就直接创建容量为10的数组是因为这样比较浪费内存空间,因而选择在添加第一个元素时进行数组的创建。