ArrayLlist简介
ArrayLlist简介
ArrayList位于jak的util包中的一个集合类,他的底层是一个动态数组。和java中的数组相比ArrayList可以动态扩容,其实ArrayList的动态扩容原理也很简单
就是在堆中开辟一个新的连续存储空间,然后将老的数组复制到新的数组空间中,主要是通过System.arraycopy()方法进行扩容的。
ArrayList的继承结构
ArrayList的属性
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
private static final long serialVersionUID = 8683452581122892189L;//这个是序列化id保证jvm对字节流进行反序列化时候检验class版本是否一致
private transient Object[] elementData;//这个属性是Arraylist中存储对象的数组
private int size;//表示ArrayList中存放的对象个数,切记他不是elementData的长度,因为elementData的中不一定存满了对象
ArrayList的构造函数
/*
无参数构造函数默认设置容量为10的ArrayList对象
*/
public ArrayList() {
this(10);
}
/*
这个带有初始化容量的构造函数,构造ArrayList对象为elementData属性赋值
*/
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
/*
这个构造函数传入一个集合对象,把传入的集合对象的元素
*/
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
size = elementData.length;
// 判断当前传入的集合元素是不是Object类型
if (elementData.getClass() != Object[].class)
//如果传入集合存放的元素不是Object对象则将其转换成Object对象
elementData = Arrays.copyOf(elementData, size, Object[].class);
}
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
//创建指定长度的Object数组
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;
}
ArrayList的普通方法
add方法有两个一个是带一个参数的 一个是带两个参数的
add(E e)
public boolean add(E e) {
//当添加元素时第一步先是确保elementData数组长度还能够存放一个元素,如果不够的话就要扩容
ensureCapacityInternal(size + 1); // Increments modCount!!
//将新添加的元素放在数组尾部
elementData[size++] = e;
//如果添加成功就返回true
return true;
}
private void ensureCapacityInternal(int minCapacity) {
//显示让modCount进行自增 这个属性主要是在迭代的时候判断是否有其他线程正在修改集合
//或者自身是否修改集合,通过这个值迭代器在迭代过程中可以快速失败 fast-favouil后面会讲
modCount++;
//判断当前我们需要的数组长度是否比elementData长度长,如果需要的长度更长
//这个时候我们当前集合持有的数组不够存放元素就得扩容
if (minCapacity - elementData.length > 0)
//扩容的方法
grow(minCapacity);
}
private void grow(int minCapacity) {
// 获取当前集合持有的数组长度
int oldCapacity = elementData.length;
//通过位运算对数组长度加0.5就是新的长度是原始长度的1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
//如果扩容后新的数组长度大于需要存储的长度,那么这时候我们的数组长度就确定下来了
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
//继续判断 如果新的长度比MAX_ARRAY_SIZE(Integer.MAX_VALUE - 8)值还大
//就让MAX_ARRAY_SIZE作为最大值,因为int值是4个字节长度
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
//将集合原来持有的数组拷贝到新的数组上面
elementData = Arrays.copyOf(elementData, newCapacity);
}
add(int index, E element)
public void add(int index, E element) {
//这个方法很简单就是判断插入的位置是不是符合要求
//不能小于0也能大于集合的长度 否则就抛出异常
rangeCheckForAdd(index);
//这个和add方法一样就是判断是否需要扩容,如果需要就进行1.5倍扩容
ensureCapacityInternal(size + 1);
//这个方法是对数组进行拷贝,注意他拷贝的数组源和目标数组是同一个数组等下画图说明
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
//上面这个拷贝方法运行后,在数组索引index位置处就可以把需要插入的元素插入这个位置
elementData[index] = element;
size++;
}
如上图所示假如我们调用方法add(b,2),首先我们先给数组扩容
然后将数组在索引2以后的元素往后移动一位
将索引为2这个位置空出来留个新元素插入
get(int index)
public E get(int index) {
//这个方法检查index是不是在size范围之内
rangeCheck(index);
//直接通过索引定位到元素
return elementData(index);
}
remove方法这里我们重点分析方法参数为索引值和对象的两个方法
remove(Int index)
//通过指定的索引位置来删除元素
public E remove(int index) {
//判断index索引是否在size范围之内
rangeCheck(index);
//因为remove操作是对元素进行删除 索引modCount需要自增
modCount++;
//通过指定索引拿到需要删除的元素
E oldValue = elementData(index);
//numMoved表示拷贝数组时候需要拷贝的位数 等下画图说明,语言不好表达
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
//因为整改数组拷贝的方向是向左边移动,所以将末尾的元素设置为null,方便垃圾回收器回收
elementData[--size] = null; // Let gc do its work
//最后返回删除的元素
return oldValue;
}
remove(Object o)
public boolean remove(Object o) {
//首先判断需要移除的元素是为null
if (o == null) {
//遍历集合,找到元素为null的索引
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
//移除元素的方法
fastRemove(index);
return true;
}
} else {
//遍历每个元素然后通过equals方法进行比较判断相当与否
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
//移除元素的方法
fastRemove(index);
return true;
}
}
return false;
}
//这个方法就是将整个数组从指定索引位置向左边移动一位,然后将末尾元素设置为null
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; // Let gc do its work
}
//不难发现这种通过移除指定元素的方法他只能找到从索引位置为0的位置开始寻找 找到最近的相同的元素进行删除,而不是删除所有的与其相同的元素
上述列举的三种方法一个是给集合增加元素,删除元素,查找元素,其中增加和删除方法主要是通过数组复制来实现的,数组复制这个操作需要在内存中开辟新的存储空间相当耗费资源,所以add方法是比较慢的。相比较来说get方法直接通过索引定位到集合元素的位置,所以说ArrayList查询元素块,增删元素慢是有道理可寻的。
有了上面的基础下面分析一下带有集合参数的添加和删除方法
addAll(Collection<? extends E> c)
public boolean addAll(Collection<? extends E> c) {
//将集合对象转换成数组,这里我列出来了ArrayList中集合转换为数组代码
//ArrayList中最终是通过System.arraycopy拷贝方法获取到数组的
//不同的集合类对于这个方法的实现不一样,以后分析其他类的时候一并分析
Object[] a = c.toArray();
int numNew = a.length;
//对集合进行扩容
ensureCapacityInternal(size + numNew); // Increments modCount
//将传入的集合对象中的元素添加到当前集合对象的末尾
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
//通过这个可以判断当我们传入一个长度为0的集合,方法的返回值为false
return numNew != 0;
}
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
public static <T> T[] copyOf(T[] original, int newLength) {
return (T[]) copyOf(original, newLength, original.getClass());
}
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
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;
}
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)
//这个拷贝呢是把从指定索引位置的元素向右移动numMoved空出来的位置用来插入新的数组
System.arraycopy(elementData, index, elementData, index + numNew,
numMoved);
//将数组插入到上一步空出来的位置当中
System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}
removeAll(Collection<?> c)
public boolean removeAll(Collection<?> 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)
//找到不相同的元素覆盖存放 依次从当前集合索引为0的位置开始存放
//索引在0,w位置的元素是不相同的,后面部分元素则是相同的
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
//当r!=size说明前面的for循环中途发生异常。这个时候把发生异常时候索引r
//之后的元素覆盖存放到w位置处
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
//将w位置后面的元素设置为null,这部分元素就是和传入集合中的元素相同
if (w != size) {
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
retainAll(Collection<?> c)
//移除和传入集合不相同的元素 也就是保留当前集合和传入的参数集合交集
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 {
//这个循环和removeAll方法的循环刚好相反
//这里是循环找到两个集合相等的元素保留在现有集合从索引0位置依次向后递增保留
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;
}
//去掉末尾的元素,因为循环完之后相等的元素的最大索引是w,w之后的元素已经没存在的意义了
if (w != size) {
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
ArrayLlist的迭代器
ArrayList迭代器有两种 一种是ListIterator 这个迭代器他可以从两个方向迭代遍历集合 从前向后或者从后向前
另一种是Iteartor这个迭代器的迭代方向只能往后进行迭代
//指定游标的位置
public ListIterator<E> listIterator(int index) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: "+index);
return new ArrayList.ListItr(index);
}
//没有指定游标的位置 默认就从游标为0的位置开始迭代
public ListIterator<E> listIterator() {
return new ArrayList.ListItr(0);
}
//获取迭代器 从这个方法可以看出他是ArrayList的一个内部类
public Iterator<E> iterator() {
return new ArrayList.Itr();
}
private class Itr implements Iterator<E> {
//迭代器的游标
int cursor;
//每进行一次迭代后,上一次的位置 初始值设置为-1
int lastRet = -1;
//这个是集合修改的次数 每次对集合进行增删改这个值就会自增1
int expectedModCount = modCount;
public boolean hasNext() {
//判断是否还能进行下一次迭代,如果游标的位置没有到末尾就可以在进行下一次迭代
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
//判断modeCount是否被修改 如果改了就直接抛出异常 这就是迭代器的快速失败原理
checkForComodification();
//我们获取Iterator对象后初始化游标应该为0
//随着每次迭代这个游标值会自增 如果大于当前集合的长度就抛出异常
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
//进一步判断是否有其他线程修改了集合,
if (i >= elementData.length)
throw new ConcurrentModificationException();
//将游标加1
cursor = i + 1;
//给lastRet变量赋值 保留迭代前的游标位置
return (E) elementData[lastRet = i];
}
//通过迭代器删除集合元素 ,因为这个方法他对expectedModCount变量
//重新进行赋值,使得expectedModCount和当前集合修改次数一致,这样我们
//在遍历的时候就不会抛出异常了
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
private class ListItr extends ArrayList.Itr implements ListIterator<E> {
ListItr(int index) {
super();
cursor = 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;
if (i < 0)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i;
//获取前一个游标值位置的元素 并将记录这个操作的游标值于lastRet变量中
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();
}
}
}
ArrayList的视图SubList
//获取ArrayList的视图对象 简单来说就是从母体中截取了一段集合的ArrayList
//这样做的好处就是可以给操作人分配他只能操作的那一部分,其他部分对他是不可见的
//相当于对ArrayList一个简单的权限控制
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new ArrayList.SubList(this, 0, fromIndex, toIndex);
}
static void subListRangeCheck(int fromIndex, int toIndex, int size) {
//判断视图的开始和结束位置是否符合要求
if (fromIndex < 0)
throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
if (toIndex > size)
throw new IndexOutOfBoundsException("toIndex = " + toIndex);
if (fromIndex > toIndex)
throw new IllegalArgumentException("fromIndex(" + fromIndex +
") > toIndex(" + toIndex + ")");
}
private class SubList extends AbstractList<E> implements RandomAccess {
private final AbstractList<E> parent;
private final int parentOffset;
private final int offset;
int size;
SubList(AbstractList<E> parent,
int offset, int fromIndex, int toIndex) {
//视图的母体对象
this.parent = parent;
//视图从母体对象中开始的索引位置
this.parentOffset = fromIndex;
//偏移量
this.offset = offset + fromIndex;
//视图的长度
this.size = toIndex - fromIndex;
//当前集合的修改次数
this.modCount = ArrayList.this.modCount;
}
public E set(int index, E e) {
//检查index的位置是否符合要求
rangeCheck(index);
//判断母体集合是否被修改了,如果修改了就直接抛出异常
checkForComodification();
E oldValue = ArrayList.this.elementData(offset + index);
//更新集合元素
ArrayList.this.elementData[offset + index] = e;
return oldValue;
}
public E get(int index) {
//检查index的位置是否符合要求
rangeCheck(index);
//判断母体集合是否被修改了,如果修改了就直接抛出异常
checkForComodification();
//获取元素
return ArrayList.this.elementData(offset + index);
}
public int size() {
//判断母体集合是否被修改了,如果修改了就直接抛出异常
checkForComodification();
return this.size;
}
public void add(int index, E e) {
rangeCheckForAdd(index);
checkForComodification();
//调用母体的add方法
parent.add(parentOffset + index, e);
this.modCount = parent.modCount;
this.size++;
}
public E remove(int index) {
rangeCheck(index);
checkForComodification();
//调用母体的remove方法
E result = parent.remove(parentOffset + index);
this.modCount = parent.modCount;
this.size--;
return result;
}
protected void removeRange(int fromIndex, int toIndex) {
checkForComodification();
parent.removeRange(parentOffset + fromIndex,
parentOffset + toIndex);
this.modCount = parent.modCount;
this.size -= toIndex - fromIndex;
}
public boolean addAll(Collection<? extends E> c) {
return addAll(this.size, c);
}
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index);
int cSize = c.size();
if (cSize==0)
return false;
checkForComodification();
//调用母体的addAll方法
parent.addAll(parentOffset + index, c);
this.modCount = parent.modCount;
this.size += cSize;
return true;
}
public Iterator<E> iterator() {
return listIterator();
}
//迭代器和母体的不同之处就是加入了一个偏移量,每次遍历的时候把偏移量算上去
public ListIterator<E> listIterator(final int index) {
checkForComodification();
rangeCheckForAdd(index);
final int offset = this.offset;
return new ListIterator<E>() {
int cursor = index;
int lastRet = -1;
int expectedModCount = ArrayList.this.modCount;
public boolean hasNext() {
return cursor != ArrayList.SubList.this.size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= ArrayList.SubList.this.size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (offset + i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[offset + (lastRet = i)];
}
public boolean hasPrevious() {
return cursor != 0;
}
@SuppressWarnings("unchecked")
public E previous() {
checkForComodification();
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (offset + i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i;
return (E) elementData[offset + (lastRet = i)];
}
public int nextIndex() {
return cursor;
}
public int previousIndex() {
return cursor - 1;
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.SubList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = ArrayList.this.modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.set(offset + lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void add(E e) {
checkForComodification();
try {
int i = cursor;
ArrayList.SubList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = ArrayList.this.modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (expectedModCount != ArrayList.this.modCount)
throw new ConcurrentModificationException();
}
};
}
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new ArrayList.SubList(this, offset, fromIndex, toIndex);
}
private void rangeCheck(int index) {
if (index < 0 || index >= this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private void rangeCheckForAdd(int index) {
if (index < 0 || index > this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+this.size;
}
private void checkForComodification() {
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
}
}