初始容量为0,当第一个元素进来后,容量设置为10
private static final int DEFAULT_CAPACITY = 10;
private static final Object[] EMPTY_ELEMENTDATA = {};
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData; // non-private to simplify nested class access
ArrayList中 用来存储数组的对象数组 这个对象是transient 的,即不可被序列化的。
由此可见,ArrayList底层实际是在维护一个对象数组
//可以通过改构造函数来初始化容量。
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);
}
}
//默认构造函数
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
//使用已经存在的集合来进行初始化
public ArrayList(Collection<? extends E> c) {//参数的意思是:形参集合的参数必须是E(是ArrayList中指定的泛型)的子类,而且c是不可以执行add的。
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)//如果不是Object数组类型,则需要复制(存在强转)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;//当集合的长度为空时,使用本类常量空集合,因为外来内存地址的不可信
}
}
补充:<? extends E>:不可以add,可以get(但是必须使用E来接受元素);<? super E>:可以add(E和E的子类),也可以get(但是类的信息会丢失,使用Object引用来接受。
//数组工具类public class Arrays{......}
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
//将集合的大小修剪为集合的长度。
/**
* Trims the capacity of this <tt>ArrayList</tt> instance to be the
* list's current size. An application can use this operation to minimize
* the storage of an <tt>ArrayList</tt> instance.
*/
public void trimToSize() {
modCount++;//这个是修改次数
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
//下面是扩充容量
private void grow(int minCapacity) {//当第一个元素进来后就会初始化容量为10,一直到8(8+4-10>0)会将容量扩充到12,9对应13,10对应15
// 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;
}
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
public static final int MAX_VALUE = 0x7fffffff;
//这个方法使用到了Object的equals()方法,也就是传进来的对象一定要重写了Object对象的equals方法,否则为地址比较。
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;
}
//Object的equals方法
public boolean equals(Object obj) {
return (this == obj);
}
//是否包含调用了indexOf
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
//克隆方法
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
//protected transient int modCount = 0;AbstractList中的成员变量
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
}
//转化为数组,底层用的是Arrays的方法
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
public E get(int index) {
rangeCheck(index);//判断参数合法性:index>size?
return elementData(index);
}
//set方法会返回被覆盖的值
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
//永远都返回true的方法
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
//在指定位置添加一个元素
public void add(int index, E element) {
rangeCheckForAdd(index);//index>size||index<0
ensureCapacityInternal(size + 1); // Increments modCount!!
//参数分别是:源数组,源数组中开始拷贝的位置,目标数组,目标数组中开始放元素的位置,拷贝的长度
System.arraycopy(elementData, index, elementData, index + 1,
size - index);//也就是将插入位置后的所有元素后移一位。
elementData[index] = element;
size++;
}
//System类的方法(public final class System)
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
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;
}
//根据元素移除,之所有分情况,是因为o为null是不能调用equals()方法。
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);//调用了System.arraycopy
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
//清除
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
//将另一个集合加入本list中
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);
//再将腾出的位置放入a数组。
System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}
//这个方法没有进行参数的合法性判断,可能会抛出IndexOutOfBoundsException异常
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// clear to let GC do its work
int newSize = size - (toIndex-fromIndex);
for (int i = newSize; i < size; i++) {
elementData[i] = null;
}
size = newSize;
}
//批量移除
// * Removes from this list all of its elements that are contained in the
// * specified collection.只要出现在c中的就移除掉
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
//批量保留
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
//这里用到了Object类的一个静态方法,以后可以用这个来代替自己写的空判断了,逼格高一点
public static <T> T requireNonNull(T obj) {
if (obj == null)
throw new NullPointerException();
return obj;
}
//批量移除实现,有修改过就返回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++)//从左往右走,发现在c中包含有的就排队留下(假设为true)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
//即使c.contains()抛出了异常,也要对已经完成的remove工作做收尾处理。
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;
}
后面的是迭代器的,有需要了解的可以自己看下,哈哈。
private static final int DEFAULT_CAPACITY = 10;
private static final Object[] EMPTY_ELEMENTDATA = {};
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData; // non-private to simplify nested class access
ArrayList中 用来存储数组的对象数组 这个对象是transient 的,即不可被序列化的。
由此可见,ArrayList底层实际是在维护一个对象数组
//可以通过改构造函数来初始化容量。
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);
}
}
//默认构造函数
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
//使用已经存在的集合来进行初始化
public ArrayList(Collection<? extends E> c) {//参数的意思是:形参集合的参数必须是E(是ArrayList中指定的泛型)的子类,而且c是不可以执行add的。
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)//如果不是Object数组类型,则需要复制(存在强转)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;//当集合的长度为空时,使用本类常量空集合,因为外来内存地址的不可信
}
}
补充:<? extends E>:不可以add,可以get(但是必须使用E来接受元素);<? super E>:可以add(E和E的子类),也可以get(但是类的信息会丢失,使用Object引用来接受。
//数组工具类public class Arrays{......}
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
//将集合的大小修剪为集合的长度。
/**
* Trims the capacity of this <tt>ArrayList</tt> instance to be the
* list's current size. An application can use this operation to minimize
* the storage of an <tt>ArrayList</tt> instance.
*/
public void trimToSize() {
modCount++;//这个是修改次数
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
//下面是扩充容量
private void grow(int minCapacity) {//当第一个元素进来后就会初始化容量为10,一直到8(8+4-10>0)会将容量扩充到12,9对应13,10对应15
// 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;
}
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
public static final int MAX_VALUE = 0x7fffffff;
//这个方法使用到了Object的equals()方法,也就是传进来的对象一定要重写了Object对象的equals方法,否则为地址比较。
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;
}
//Object的equals方法
public boolean equals(Object obj) {
return (this == obj);
}
//是否包含调用了indexOf
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
//克隆方法
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
//protected transient int modCount = 0;AbstractList中的成员变量
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
}
//转化为数组,底层用的是Arrays的方法
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
public E get(int index) {
rangeCheck(index);//判断参数合法性:index>size?
return elementData(index);
}
//set方法会返回被覆盖的值
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
//永远都返回true的方法
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
//在指定位置添加一个元素
public void add(int index, E element) {
rangeCheckForAdd(index);//index>size||index<0
ensureCapacityInternal(size + 1); // Increments modCount!!
//参数分别是:源数组,源数组中开始拷贝的位置,目标数组,目标数组中开始放元素的位置,拷贝的长度
System.arraycopy(elementData, index, elementData, index + 1,
size - index);//也就是将插入位置后的所有元素后移一位。
elementData[index] = element;
size++;
}
//System类的方法(public final class System)
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
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;
}
//根据元素移除,之所有分情况,是因为o为null是不能调用equals()方法。
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);//调用了System.arraycopy
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
//清除
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
//将另一个集合加入本list中
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);
//再将腾出的位置放入a数组。
System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}
//这个方法没有进行参数的合法性判断,可能会抛出IndexOutOfBoundsException异常
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// clear to let GC do its work
int newSize = size - (toIndex-fromIndex);
for (int i = newSize; i < size; i++) {
elementData[i] = null;
}
size = newSize;
}
//批量移除
// * Removes from this list all of its elements that are contained in the
// * specified collection.只要出现在c中的就移除掉
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
//批量保留
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
//这里用到了Object类的一个静态方法,以后可以用这个来代替自己写的空判断了,逼格高一点
public static <T> T requireNonNull(T obj) {
if (obj == null)
throw new NullPointerException();
return obj;
}
//批量移除实现,有修改过就返回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++)//从左往右走,发现在c中包含有的就排队留下(假设为true)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
//即使c.contains()抛出了异常,也要对已经完成的remove工作做收尾处理。
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;
}
后面的是迭代器的,有需要了解的可以自己看下,哈哈。