private static final long serialVersionUID = 8683452581122892189L;
/**
* 默认的 初始化长度10
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* 空的数组
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* 不可被序列化的存储对象 当为空时 默认第一次添加是自动扩容为10
*/
private transient Object[] elementData;
/**
*数组对象的个数
*
*/
private int size;
/**
* 有参构造 制定数组长度
*
*/
public ArrayList(int initialCapacity) {
//制定小于0抛异常
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
//创建一个制定的大小的对象
this.elementData = new Object[initialCapacity];
}
/**
* 无参创建一个空的数组此时不指定数组缓冲区长度 当第一次扩容时如果是空 那么就默扩10
*/
public ArrayList() {
super();
this.elementData = EMPTY_ELEMENTDATA;
}
/**
* 创建一个包含collection的Arraylist
*/
public ArrayList(Collection<? extends E> c) {
//把collection对象转换成数组
elementData = c.toArray();
//把数组长度赋值
size = elementData.length;
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
}
/**
* 根据实际数字size 来设置缓冲区大小
*/
public void trimToSize() {
//操作数字计数变量
modCount++;
//如果当前数组个数小于当前数组缓冲区值
if (size < elementData.length) {
//创建新的指定大小数字
elementData = Arrays.copyOf(elementData, size);
}
}
/**
* 将集合的容器增加到最小
*/
public void ensureCapacity(int minCapacity) {
int minExpand = (elementData != EMPTY_ELEMENTDATA)
// any size if real element table
? 0
// larger than default for empty table. It's already supposed to be
// at default size.
: DEFAULT_CAPACITY;
if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
}
//保证最小值
private void ensureCapacityInternal(int minCapacity) {
if (elementData == EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
//当前的最小值和elementData.length 作比较看是否需要扩容
if (minCapacity - elementData.length > 0)
grow(minCapacity);//扩容
}
/**
* The maximum size of array to allocate.
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
*扩容方法:从扩容方法可以看到 扩容的原理是copy值到新的数组,这样会消耗性能,最好在使用时能确定大小
*/
private void grow(int minCapacity) {
//获取当前数字长度
int oldCapacity = elementData.length;
//获取当前长度的1.5倍 oldCapacity>>1 是将oldCapacity右位移1位 相当于oldCapacity/2
int newCapacity = oldCapacity + (oldCapacity >> 1);
//扩容满足不了 就设置需要的长度
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
//扩容是否超过最大值限制
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
//将原来的数组copy到新的数字中
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;
}
/**
* 得到数字里的个数
*/
public int size() {
return size;
}
/**
* 是否为空
*/
public boolean isEmpty() {
return size == 0;
}
/**
* 是否包含某个元素 默认调用indexof方法
*/
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
/**
*是否包含某元素 循环比例 有就返回元素所在脚标 没有返回-1
*
*/
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 int lastIndexOf(Object o) {
if (o == null) {
for (int i = size-1; i >= 0; i--)
if (elementData[i]==null)
return i;
} else {
for (int i = size-1; i >= 0; i--)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
/**
*
*/
public Object clone() {
try {
@SuppressWarnings("unchecked")
//调用父类clone()生成新对象
ArrayList<E> v = (ArrayList<E>) 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();
}
}
/**
*把对象变成array数字 利用Arrayscopy函数
*/
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
/*
*返回一个包含ArrayList中所有元素的数组
*/
@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;
}
//获取某个脚标的元素
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
/**
*得到指定脚标某元素
*/
public E get(int index) {
//检查是否索引越界
rangeCheck(index);
//获取某个脚标的元素
return elementData(index);
}
/**
* 制定脚标位置插入值 返回其原来的值
*/
public E set(int index, E element) {
//检查索引是否越界
rangeCheck(index);
/获取其原来值
E oldValue = elementData(index);
//替换成新值
elementData[index] = element;
return oldValue;
}
/**
*添加新元素 返回boolean类型
*/
public boolean add(E e) {
//判断是否需要扩容
ensureCapacityInternal(size + 1);
//在数组最末尾添加新元素
elementData[size++] = e;
return true;
}
/**
* 在指定位置添加元素
*/
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 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);
//最后一个元素设置null
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
/**
*删除指定某个元素(第一次出现) 循环遍历得到指定元素脚标调用fastRemove() 返回boolean类型;
*/
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;
}
/*
*快速删除指定元素
*/
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
}
/**
* 清空arrayList 注意 此清空不会改变容量的大小
*/
public void clear() {
modCount++;
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
/**
*按照c的迭代器所返回的元素顺序,将c中的所有元素添加到此列表的尾部
*/
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;
}
/**
* 删除fromindex -toindex之间的元素
*/
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
//删除后的元素个数
int numMoved = size - toIndex;
//将删除索引后面的元素复制到以fromIndex为起始位置的存储空间中去
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
int newSize = size - (toIndex-fromIndex);
for (int i = newSize; i < size; i++) {
elementData[i] = null;
}
size = newSize;
}
/**
* 检查是否索引越界
*/
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* A version of rangeCheck used by add and addAll.
*/
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
*
*/
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
/**
* 清空ArrayList包含collection的元素
*/
public boolean removeAll(Collection<?> c) {
return batchRemove(c, false);
}
/**
* 删除ArrayList中除包含在Collection中的元素,和removeAll相反
*/
public boolean retainAll(Collection<?> 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;
}
/**
* 将ArrayList的所有元素写入到输出流中
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
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();
}
}
}