序言
- ArrayList 属于List集合,具有查找快速,不用担心超出容量等的优点。日常使用的频率非常高。
- 本文将从源码分析其构造方法,自动扩容机制实现,以及基本的增删改查操作,遍历方法等各个角度介绍。
ArrayList
1.1 继承关系
java.lang.Object
↳ java.util.AbstractCollection<E>
↳ java.util.AbstractList<E>
↳ java.util.ArrayList<E>
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable {}
1.2 重要变量
/**
*此变量位于AbstractList中,用于保证集合唯一性,因为ArrayList不是线程安全的,所以当有两个及其以上线程同时修改ArrayList,
*系统不知道帮我们保存修改前还是修改后的List,就会抛出ConcurrentModificationException异常。
*/
protected transient int modCount = 0;
/**
* ArrayList真正用于存放数据的数组。关键字transient:是在序列化时,不序列化该变量。
*/
transient Object[] elementData;
1.3 构造函数
/**
* 构造方法1:默认数组长度。这是最常用方法--系统提供的 生成一个空的数组,默认长度为10.
*/
public ArrayList() {
//elementData是数组,用于存放数据。空数组,在添加元素时,会重新生成一个长度为10的数组。
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
* 构造方法2: 制定数组长度。如果提前知道数据长度,推荐使用此构造方法,指定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);
}
}
/**
*构造方法3:给ArrayList直接传入集合作为初始数据。
*/
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;
}
}
1.4 扩展
Collection.toArray():是一个接口,每个类实现不同。(下面会多次用到,提前解释清楚)
ArrayList.toArray():调用Arrays.copyOf(elementData, size)
/**
*复制生成数组。
**/
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
@SuppressWarnings("unchecked")
//这个时候系统会判断传入的数据是不是基本数据类型,如果是则直接定义数组返回,
//如果不是则传入Arrays.newArray(Class<?> componentType, int size)方法处理
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;
}
- 我们接着分析Arrays.newArray方法。
/**
*根据传入的数据类型,生成对应的数组。分别对应不同的数据类型。
*/
private static Object newArray(Class<?> componentType, int size) throws NegativeArraySizeException {
if (!componentType.isPrimitive()) {
return createObjectArray(componentType, size);
} else if (componentType == char.class) {
return new char[size];
} else if (componentType == int.class) {
return new int[size];
} else if (componentType == byte.class) {
return new byte[size];
} else if (componentType == boolean.class) {
return new boolean[size];
} else if (componentType == short.class) {
return new short[size];
} else if (componentType == long.class) {
return new long[size];
} else if (componentType == float.class) {
return new float[size];
} else if (componentType == double.class) {
return new double[size];
} else if (componentType == void.class) {
throw new IllegalArgumentException("Can't allocate an array of void");
}
throw new AssertionError();
}
2.1 添加元素(增)
/**
* add方法1:按顺序增加元素。
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // 2.2 ArrayList的扩容机制。
elementData[size++] = e;
return true;
}
/**
* add方法2:在指定位置添加元素。
*/
public void add(int index, E element) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
//List数据自适应长度的保证。
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
/**
* add方法3:加入集合元素
*/
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;
}
/**
*add方法4:在制定位置添加集合元素。
*/
public boolean addAll(int index, Collection<? extends E> c) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(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.2 ArrayList扩容机制。
日常使用,我们并不需要去关注ArrayList的容量,在需要的时候系统会帮我们自动扩容,而具体的扩容机制就是由下面的方法实现的。(面试时问到ArrayList,应说出其扩容机制的原理。)
/**
*判断容量。
*/
public void ensureCapacity(int minCapacity) {
//获取ArrayList的可扩展度。
int minExpand = (elementData != EMPTY_ELEMENTDATA)
? 0: DEFAULT_CAPACITY; // 三元表达式=> 如果为空数组,未添加过数据,则初始化为长度为10的数组。
if (minCapacity > minExpand) {//如果不能满足需要,则进行扩容处理。
ensureExplicitCapacity(minCapacity);
}
}
private void ensureCapacityInternal(int minCapacity) {
//如果elementData为空,则是第一次添加元素。
//取默认容量和需要容量的最大值。
if (elementData == EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;// 标记扩容开始,此时如果对ArrayList进行增删,则会抛出异常。
// 需要的容量大于现有的容量则扩容。
if (minCapacity - elementData.length > 0)
grow(minCapacity);//下面介绍。
}
/**
* ArrayList扩容的实现方法。
*/
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
//设置新容量为oldCapacity的1.5倍。
int newCapacity = oldCapacity + (oldCapacity >> 1);
//如果1.5倍容量依旧不能满意需求,则直接将容量设置需要容量。
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
//如果新容量超过可设定的最大值,则默认为最大值。
if (newCapacity - MAX_ARRAY_SIZE > 0)//MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8
newCapacity = hugeCapacity(minCapacity);// 是否需要最大容量。
// 生成数组。
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;
}
- 结论:ArrayList的自适应是通过系统扩容完成的,由于每个数组是固定长度,所以每次扩容需要新建数组,再将数据复制到新数组。
3 删除元素(删)
/**
* 删除方法1:删除指定位置数据,此方法最搞笑,不需要遍历数组。
*/
public E remove(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
modCount++;
E oldValue = (E) elementData[index];
int numMoved = size - index - 1;
//删除成功后,将index后面的数据,全部向前移一位。(如果是最后一位,则不需要移动)
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // 将指针置为空,好让系统能及时回收。
//返回被移除的数据。
return oldValue;
}
/**
* 删除方法2:由于不知道需要删除元素的位置,所以只能遍历先查找。
*/
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;
}
/**
* 删除方法3:移除集合c内的全部元素。
*/
public boolean removeAll(Collection<?> c) {
return batchRemove(c, false);
}
//
/**
* 删除方法4:移除不在集合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 {
for (; r < size; r++)
//判断集合c是否包含ArrayList里的元素。
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// contains方法可能抛出异常,在此处理for循环未处理完的数据。
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
if (w != size) {
//遍历w以后的位置,将不需要的元素位置全部置为null,方便垃圾回收期回收。
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
/**
* 删除方法5:清除全部数据。长度置为0.
*/
public void clear() {
modCount++;
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
4. 修改元素(改)- ArrayList的优势之一,能根据角标快速定位Item位置,进行修改。无需遍历。
/**
*修改指定位置元素,将原来的元素返回。
*/
public E set(int index, E element) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
E oldValue = (E) elementData[index];
elementData[index] = element;
return oldValue;
}
5.查找元素(查)- get方法用得最多,根据角标定位也很快。建议使用。
/**
*查找方法1: 判断是否包含o元素。
*/
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
/**
* 查找方法2:正常顺序查找,获取元素首次出现的位置。
* 返回-1则查找失败,成功则返回元素所在位置。
*/
public int indexOf(Object o) {
//因为ArrayList支持null元素,所以需分开处理。
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;
}
/**
*查找方法3:倒序查找,获取元素首次出现的位置。
*/
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;
}
/**
* 查找方法4:获取指定位置元素。(知道位置的情况下,此方法最快)
*/
public E get(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
return (E) elementData[index];
}
给大家介绍一下ArrayList三种不同的遍历方法,以及其使用场景。
- 方法一:
int len = list.size();//提前保存List长度,可提高程序运行效率。
for (int i = 0; i < len; i++){
list.get(i);//通过指针获取元素。
}
- 方法二:
for (String s : list){//方法一的简写形式。
s.length();
}
- 方法三:通过迭代器。方法一和方法二,用于查找元素,如果需要修改或者删除元素,建议选择方法三。
ListIterator<String> listIterator = list.listIterator();//获取迭代器。
while (listIterator.hasNext()){//判断是否还存在元素。
String s = listIterator.next();//获取元素。
listIterator.remove();//移除元素。
listIterator.set("New");//修改元素。
}
结论
通过对ArrayList的增删改查以及扩容机制的分析,相信大家以及对其有了更深入的了解,下面再简单介绍一下其优缺点。
- 优点
1、ArrayList 可存放null元素,遍历速度快。
2、ArrayList 底层存放数据是数组,能快速定位到指定位置。
3、ArrayList 实现了自动扩容机制,无需担心超出容量。 - 缺点
1、ArrayList 在不知道index的情况下,获取指定元素,只能遍历集合。建议使用的时候,多用get(int index)方法。
2、ArrayList 的自动扩容机制,也是通过新建数组,复制元素实现,因为数组长度是不可变的。建议在构造ArrayList时,指定自己需要的大小。
3、ArrayList的删除,增加操作时,可能会触发数组新建或复制,增加程序开销。(如需频繁增删元素,建议使用LinkedList)
4、ArrayList为 非线程安全的集合,使用时需注意多线程的调用。
网友评论