目录
一:ArrayList的成员变量
二:ArrayList的构造方法
1.创建ArrayList
2.构造方法
3.源码分析
三:ArrayList的增删改查操作
1.ArrayList的add方法源码分析
①添加到指定位置add(int index, E element)
②添加所有addAll(Collection c)
③添加所有到指定位置addAll(int index, Collection c)
2.ArrayList的remove方法源码分析
①删除指定索引元素 E remove(int index)
②删除指定值的元素 remove(Object o)
3.ArrayList的get方法源码分析
①获取单个元素get(int index)
4.ArrayList的set方法源码分析
5.ArrayList的contains方法源码分析
6.遍历元素 iterator()
四:其他
判断元素是否存在
总结
一:ArrayList的成员变量
private static final long serialVersionUID = 8683452581122892189L; //序列版本号
private static final int DEFAULT_CAPACITY = 10;//默认数组元素的初始容量为10
private static final Object[] EMPTY_ELEMENTDATA = {};//空元素对象数组
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};//默认容量的空数据数组
transient Object[] elementData; // 数组元素对象,list中的元素就存在这里
private int size;//添加的元素的数量
二:ArrayList的构造方法
1.创建ArrayList
ArrayList
2.构造方法
ArrayList
2.构造方法
ArrayList():构造一个初始容量为10的空列表
ArrayList(Collection c):构造一个包含指定元素的列表
ArrayList( int initialCapcity ):构造一个具有初始容量值得空列表
3.源码分析
public ArrayList(int initialCapacity) { //初始化容量
if (initialCapacity > 0) { //判断传入的参数值
this.elementData = new Object[initialCapacity];//把传入的容量作为数组的初始容量
} else if (initialCapacity == 0) {//如果传入的是0
this.elementData = EMPTY_ELEMENTDATA;//初始化为空数组
} else {
throw new IllegalArgumentException("Illegal Capacity: "+ //传入的如果小于0,就抛出参数违规异常
initialCapacity);
}
}
public ArrayList() { //空构造方法
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;//空对象数组初始化,其容量为10
}
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;
}
}
三:ArrayList的增删改查操作
1.ArrayList的add方法源码分析
①添加到指定位置add(int index, E element)
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) { //专为add方法增加的返回检查
if (index < 0 || index > this.size)//如果传入的参数小于0或者大于数组已添加元素的个数
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));//抛出异常
}
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;//定义数组最大的值为Integer最大值-8
private void ensureCapacityInternal(int minCapacity) {//确保容量
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { //如果数组元素等于默认的空数组容量
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);//取默认的容量和指定的容量的较大值
}
ensureExplicitCapacity(minCapacity);//传入 ensureExplicitCapacity方法确保扩展的容量
}
private void ensureExplicitCapacity(int minCapacity) {/确保扩展容量
modCount++;//修改次数+1
// overflow-conscious code
if (minCapacity - elementData.length > 0)//如果指定的容量大于数组容量
grow(minCapacity);//调用gorw方法
}
private void grow(int minCapacity) { //传入指定的容量
// overflow-conscious code
int oldCapacity = elementData.length;//取旧的数组元素的长度
int newCapacity = oldCapacity + (oldCapacity >> 1);//旧长度除以2+长度赋予新长度(相当于扩容1.5倍)
if (newCapacity - minCapacity < 0)//如果新长度小于指定的容量
newCapacity = minCapacity;//把新计算的长度赋予指定的容量
if (newCapacity - MAX_ARRAY_SIZE > 0)//如果新容量>最大数组大小
newCapacity = hugeCapacity(minCapacity);//调用bugeCapcaity方法
elementData = Arrays.copyOf(elementData, newCapacity);//复制数组
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // 如果指定容量小于0
throw new OutOfMemoryError();//抛出异常内存错误
return (minCapacity > MAX_ARRAY_SIZE) ?//如果指定容量大于最大数组大小返回int的最大值
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;//否则返回最小数组大小
}
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
1.ArrayList的add方法源码分析
①添加到指定位置add(int index, E element)
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) { //专为add方法增加的返回检查
if (index < 0 || index > this.size)//如果传入的参数小于0或者大于数组已添加元素的个数
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));//抛出异常
}
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;//定义数组最大的值为Integer最大值-8
private void ensureCapacityInternal(int minCapacity) {//确保容量
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { //如果数组元素等于默认的空数组容量
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);//取默认的容量和指定的容量的较大值
}
ensureExplicitCapacity(minCapacity);//传入 ensureExplicitCapacity方法确保扩展的容量
}
private void ensureExplicitCapacity(int minCapacity) {/确保扩展容量
modCount++;//修改次数+1
// overflow-conscious code
if (minCapacity - elementData.length > 0)//如果指定的容量大于数组容量
grow(minCapacity);//调用gorw方法
}
private void grow(int minCapacity) { //传入指定的容量
// overflow-conscious code
int oldCapacity = elementData.length;//取旧的数组元素的长度
int newCapacity = oldCapacity + (oldCapacity >> 1);//旧长度除以2+长度赋予新长度(相当于扩容1.5倍)
if (newCapacity - minCapacity < 0)//如果新长度小于指定的容量
newCapacity = minCapacity;//把新计算的长度赋予指定的容量
if (newCapacity - MAX_ARRAY_SIZE > 0)//如果新容量>最大数组大小
newCapacity = hugeCapacity(minCapacity);//调用bugeCapcaity方法
elementData = Arrays.copyOf(elementData, newCapacity);//复制数组
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // 如果指定容量小于0
throw new OutOfMemoryError();//抛出异常内存错误
return (minCapacity > MAX_ARRAY_SIZE) ?//如果指定容量大于最大数组大小返回int的最大值
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;//否则返回最小数组大小
}
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
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) { //专为add方法增加的返回检查
if (index < 0 || index > this.size)//如果传入的参数小于0或者大于数组已添加元素的个数
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));//抛出异常
}
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;//定义数组最大的值为Integer最大值-8
private void ensureCapacityInternal(int minCapacity) {//确保容量
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { //如果数组元素等于默认的空数组容量
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);//取默认的容量和指定的容量的较大值
}
ensureExplicitCapacity(minCapacity);//传入 ensureExplicitCapacity方法确保扩展的容量
}
private void ensureExplicitCapacity(int minCapacity) {/确保扩展容量
modCount++;//修改次数+1
// overflow-conscious code
if (minCapacity - elementData.length > 0)//如果指定的容量大于数组容量
grow(minCapacity);//调用gorw方法
}
private void grow(int minCapacity) { //传入指定的容量
// overflow-conscious code
int oldCapacity = elementData.length;//取旧的数组元素的长度
int newCapacity = oldCapacity + (oldCapacity >> 1);//旧长度除以2+长度赋予新长度(相当于扩容1.5倍)
if (newCapacity - minCapacity < 0)//如果新长度小于指定的容量
newCapacity = minCapacity;//把新计算的长度赋予指定的容量
if (newCapacity - MAX_ARRAY_SIZE > 0)//如果新容量>最大数组大小
newCapacity = hugeCapacity(minCapacity);//调用bugeCapcaity方法
elementData = Arrays.copyOf(elementData, newCapacity);//复制数组
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // 如果指定容量小于0
throw new OutOfMemoryError();//抛出异常内存错误
return (minCapacity > MAX_ARRAY_SIZE) ?//如果指定容量大于最大数组大小返回int的最大值
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;//否则返回最小数组大小
}
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
Arraylist在添加元素的时候,首先进行的是范围检查,防止其传入的参数小于0或者超过数组的size大小,再是和默认分配的大小值进行比较,如果大于默认大小就要进行扩容。扩容的时候首先把旧数组的大小提升1.5倍,成为新数组的大小值。同时也可以看到Arrylist的大小边界是Interger的最大值,这个数字是很大的:2147483647,也就是它的最大值是这么多,这个值足以我们程序员平常进行使用!在检查完毕和扩容完毕之后,就是要进行数组的拷贝了
②添加所有addAll(Collection extends E> c)
public boolean addAll(Collection extends E> c) {
Object[] a = c.toArray();//将c集合转化为对象数组a
int numNew = a.length;//获取a对象数组的容量
ensureCapacity(size + numNew);//确保对象数组elementData有足够的容量,可以将新加入的a对象数组加进去
System.arraycopy(a, 0, elementData, size, numNew);//将对象数组a拷贝到elementData中去
size += numNew;//重新设置elementData中已加入的元素的个数
return numNew != 0;//若加入的是空集合则返回false
}
③添加所有到指定位置addAll(int index, Collection extends E> c)
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;
}
2.ArrayList的remove方法源码分析
①删除指定索引元素 E remove(int index)
public E remove(int index) {//根据指定位置移除元素
rangeCheck(index);//范围检查
modCount++;//修改次数+1
E oldValue = elementData(index);//根据数组元素的位置找到旧值
int numMoved = size - index - 1;
if (numMoved > 0)//判断是否大于0
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; //
return oldValue;//返回旧值
}
②删除指定值的元素 remove(Object o)
public boolean remove(Object o) {
if (o == null) {//移除对象数组elementData中的第一个null
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {//移除对象数组elementData中的第一个o
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; //将最后一个元素设为null,在下次gc的时候就会回收掉了
}
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;
}
2.ArrayList的remove方法源码分析
①删除指定索引元素 E remove(int index)
public E remove(int index) {//根据指定位置移除元素
rangeCheck(index);//范围检查
modCount++;//修改次数+1
E oldValue = elementData(index);//根据数组元素的位置找到旧值
int numMoved = size - index - 1;
if (numMoved > 0)//判断是否大于0
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; //
return oldValue;//返回旧值
}
②删除指定值的元素 remove(Object o)
public boolean remove(Object o) {
if (o == null) {//移除对象数组elementData中的第一个null
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {//移除对象数组elementData中的第一个o
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; //将最后一个元素设为null,在下次gc的时候就会回收掉了
}
public E remove(int index) {//根据指定位置移除元素
rangeCheck(index);//范围检查
modCount++;//修改次数+1
E oldValue = elementData(index);//根据数组元素的位置找到旧值
int numMoved = size - index - 1;
if (numMoved > 0)//判断是否大于0
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; //
return oldValue;//返回旧值
}
②删除指定值的元素 remove(Object o)
public boolean remove(Object o) {
if (o == null) {//移除对象数组elementData中的第一个null
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {//移除对象数组elementData中的第一个o
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; //将最后一个元素设为null,在下次gc的时候就会回收掉了
}
remove(Object o)需要遍历数组,remove(int index)不需要,只需要判断索引符合范围即可,所以,通常:后者效率更高。
3.ArrayList的get方法源码分析
①获取单个元素get(int index)
public E get(int index) {
rangeCheck(index);//检查索引范围
return (E) elementData[index];//返回元素,并将Object转型为E
}
```
```java
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
public E get(int index) {
rangeCheck(index);//检查索引范围
return (E) elementData[index];//返回元素,并将Object转型为E
}
```
```java
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
注意rangeCheck检查的是size的大小,也就是实际存储元素个数,而不是容器的实际容量。
4.ArrayList的set方法源码分析
set(int index,E element):用element替换index位置上的元素。
//第一步:
public E set(int index, E element) {
//检查index是否小于size,如果不是抛异常
rangeCheck(index) ;
E oldvalue = elementData(index) ;
//覆盖ArrayList中index.上的元素。
elementData[index] = element;
//返回被覆盖的元素。
return oldvalue;
}
//第二步:
private void r angeCheck(int index) {
if (index >= size) throw new IndexOutOfBoundsExcept ion(outofBoundsMsg(index));
5.ArrayList的contains方法源码分析
contains(Object o):如果包含元素o,则返回为true
indexOf( Object o ):返回此列表中指定元素的第一次出现的索引,如果列表不包含此元素,返回-1
public boolean contains (object o {
return indexof(o) >= 0;
}
public int indexof(object o) {
if (o == nu11) {
for(inti=0;i
6.遍历元素 iterator()
public Iterator iterator() {
return new Itr();
}
private class Itr implements Iterator {
int cursor = 0;//标记位:标记遍历到哪一个元素
int expectedModCount = modCount;//标记位:用于判断是否在遍历的过程中,是否发生了add、remove操作
//检测对象数组是否还有元素
public boolean hasNext() {
return cursor != size();//如果cursor==size,说明已经遍历完了,上一次遍历的是最后一个元素
}
//获取元素
public E next() {
checkForComodification();//检测在遍历的过程中,是否发生了add、remove操作
try {
E next = get(cursor++);
return next;
} catch (IndexOutOfBoundsException e) {//捕获get(cursor++)方法的IndexOutOfBoundsException
checkForComodification();
throw new NoSuchElementException();
}
}
//检测在遍历的过程中,是否发生了add、remove等操作
final void checkForComodification() {
if (modCount != expectedModCount)//发生了add、remove操作,这个我们可以查看add等的源代码,发现会出现modCount++
throw new ConcurrentModificationException();
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
}
四:其他
判断元素是否存在
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
public int indexOf(Object o) {
if (o == null) {//返回第一个null的索引
for (int i = 0; i < size; i++)
if (elementData[i] == null)
return i;
} else {//返回第一个o的索引
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;//若不包含,返回-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;
}
总结
1.ArrayList的底层是数组,初始容量是10,当数组满了之后,继续添加元素时,会扩容到原来的1.5倍+1。
2.ArrayList保存了一个modCount属性,修改集合的操作都会让其自增。如果在遍历的时候modCount被修改,则会抛出异常,产生fail-fast事件。
3.ArrayList内部还维护了一个size属性,它是用来记录数组中的实际元素个数。
size,modCount,elementData这些成员变量,都注定了ArrayList线程不安全。
4.ArrayList实现了Iterator接口,这表明遍历ArrayList使用普通for循环比使用foreach更快。
5.需要注意的是这里有一个Java集合的fail-fast事件。我们在调用add()、remove()这些修改集合的方法时,都会修改一个属性modCount。而我们在遍历集合时,首先会保存一份modCount,然后在遍历时,将保存的modCount和成员变量modCount对比,如果不一样,说明被集合已经被修改,抛出ConcurrentModificationException,产生fail-fast事件。



