ArrayList
简述
ArrayList底层是以一个Object数组实现的,默认情况下,数组大小为10,在将更多数据添加到数组列表时自动扩容。
ArrayList不是线程安全的,多线程的环境下考虑使用Collections.synchronizedList(new ArrayList(…));
,返回一个线程安全的ArrayList类,也可以使用concurrent并发包下的CopyOnWriteArrayList类。
ArrayList的iterator和listIterator方法所返回的迭代器都具有快速失败的特性,也就是在创建了迭代器之后,如果使用了除了迭代器自己的方法之外的方法去尝试对列表结构进行修改,迭代器则可能会抛出ConcurrentModificationException。
类图
ArrayList 继承了 AbstractList,实现了List, RandomAccess, Cloneable, java.io.Serializable接口,这些接口都是有它们自己的作用的。
- ArrayList 实现了 RandmoAccess 接口,即提供了随机访问功能。RandmoAccess是java中用来被List实现,为List提供快速访问功能的。在ArrayList中,我们即可以通过元素的索引快速获取元素对象;这就是快速随机访问。
- ArrayList 实现了 Cloneable接口,即覆盖了方法clone(),能被克隆。
- ArrayList 实现了 java.io.Serializable接口,这意味着ArrayList支持序列化,能通过序列化去传输。
- ArrayList与Vector不同,ArrayList 中的操作不是线程安全的。所以,建议在单线程中才使用ArrayList,而在多线程中可以选择Vector或者CopyOnWriteArrayList。
不过现在都不推荐使用Vector类,据说是因为这个类是上古的Java类,现在效率低不行。
函数说明
构造函数
ArrayList()
下面是ArrayList默认的构造函数,它会初始化一个容量为10的数组,也就是上面说到过的ArrayList默认容量大小就是10。
/**
* 构造一个初始容量为10的空列表。
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
ArrayList(int initialCapacity)
该构造函数接收一个int类型的数值来初始化ArrayList,建立一个初始化容量为传入值大小的Object数组,如果指定大小为负数,则抛出IllegalArgumentException异常。
/**
* 构造具有指定初始容量的空列表。
*
* @param initialCapacity 列表的初始容量
* @throws IllegalArgumentException 如果指定的初始容量为负数
*/
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);
}
}
ArrayList(Collection<? extends E> c)
该构造函数按照集合的迭代器返回的顺序,初始化elementData,构造一个包含指定集合元素的列表。
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray()返回的如果不是Object[]
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// 如果传入的集合没有数据,直接使用EMPTY_ELEMENTDATA,和new ArrayList(0)一样
this.elementData = EMPTY_ELEMENTDATA;
}
}
源码分析
私有字段说明
通过ArrayList的构造函数,也可以看出ArrayList内包含了两个重要的字段:elementData 和 size。
- elementData 是 Object类型的数组,它主要用于保存添加到ArrayList数组中的元素。或者我们可以通过构造函数 ArrayList(int initialCapacity)来指定它的初始容量。如果使用默认构造函数来创建ArrayList,则elementData的默认容量为10,并且elementData数组大小会随着ArrayList容量的增长而动态的增长,具体的增长方式下面会说。
- size 是elementData数组的实际大小。
- modCount(ArrayList的父类AbstractList的属性),这个变量用于快速判断该实例是否有变化,若在迭代的时候有变更,那么就抛出一个并发修改异常(ConcurrentModificationException)。也就是上文说的快速失败机制,fail-fast是Java集合的一种错误检测机制。当多个线程对集合进行结构上的改变的操作时,有可能会产生fail-fast机制。
java.util.AbstractList:
//当前列表结构被修改的次数
protected transient int modCount
- DEFAULT_CAPACITY(ArrayList的默认数组大小)
/**
* 默认初始化容量大小为10
*/
private static final int DEFAULT_CAPACITY = 10;
- EMPTY_ELEMENTDATA(用于空实例的共享空数组实例。)
/**
* 用于空实例的共享空数组实例。
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
如果上面这个字段看不懂,就去看看ArrayList(int initialCapacity)构造方法里面对它的使用就知道了。
- DEFAULTCAPACITY_EMPTY_ELEMENTDATA(用于默认大小的空实例的共享空数组实例)
/**
* 用于默认大小的空实例的共享空数组实例。 我们将此与EMPTY_ELEMENTDATA区分开来,以便在添加第一个元素时知道要膨胀多少。
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
- MAX_ARRAY_SIZE(最大数组大小)
/**
* 要分配的最大数组大小。 尝试分配更大的数组可能会导致OutOfMemoryError:请求的数组大小超过VM限制
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
方法源码解析
public void trimToSize()
将此ArrayList实例的容量调整为列表的当前大小。 应用程序可以使用此操作来最小化ArrayList实例的存储。
为什么说是当前大小呢,比如初始化ArrayList的容量大小为10,只往里添加了4个元素,那么数组内有6个位置都为null,浪费空间,使用这个方法之后,容量会调整为4,也就是列表的当前大小。
public void trimToSize() {
//列表结构修改次数加1
modCount++;
//如果列表实际大小 < elementData,调整ArrayList实例的容量调整为列表的当前大小(size)
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
public void ensureCapacity(int minCapacity)
如有必要,增加此ArrayList实例的容量,以确保它至少可以容纳由minCapacity参数指定的元素数。
/**
* 增加此ArrayList实例的容量
*
* @param minCapacity 所需的最小容量
*/
public void ensureCapacity(int minCapacity) {
int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
? 0
// 大于默认值。 它被认为是默认大小。
: DEFAULT_CAPACITY;
//如果指定大小minCapacity 大于 minExpand,进行扩容
if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
}
private void ensureExplicitCapacity(int minCapacity) {
//列表结构修改次数加1
modCount++;
// 如果指定大小大于当前列表数组缓冲区大小,则增加容量
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// 原有容量,当前数组缓存大小
int oldCapacity = elementData.length;
//新的容量=原有容量+(原有容量/2)
int newCapacity = oldCapacity + (oldCapacity >> 1);
//如果新的容量 < minCapacity,设置新的容量大小为minCapacity
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
//如果新的容量 > MAX_ARRAY_SIZE
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();
//如果期望容量 minCapacity > MAX_ARRAY_SIZE(允许分配最大值),则设置大小为 Integer.MAX_VALUE
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
public int size()
返回列表中的元素数量(数组内的真实容量)。
public int size() {
return size;
}
public boolean isEmpty()
如果此列表不包含任何元素,则返回true,该方法就是用size变量去判断数组是否为空。
public boolean isEmpty() {
return size == 0;
}
public boolean contains(Object o)
如果此列表包含指定的元素,则返回true,该方法是使用indexOf(Object o)方法去判断是否包含,若返回-1则表示没有这个元素,若返回值>=0表示包含这个元素。
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
public int indexOf(Object o)
返回此列表中第一次出现的指定元素的索引,如果此列表不包含该元素,则返回-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)
返回此列表中指定元素最后一次出现的索引,如果此列表不包含该元素,则返回-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()
返回此ArrayList实例的副本。(元素本身不会被复制)
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) 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(e);
}
}
public Object[] toArray()
以适当的顺序(从第一个元素到最后一个元素)返回包含此列表中所有元素的数组。返回的数组将是“安全的”,因为此列表不会保留对它的引用(此方法必须分配一个新数组)。
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
public E get(int index)
返回此列表中指定位置的元素。
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
//检查给定索引是否在范围内。 如果不是,则抛出适当的运行时异常。 此方法不检查索引是否为负数:如果索引为负,则抛出ArrayIndexOutOfBoundsException。
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
//根据给定的索引获取数组elementData中对应位置的元素
E elementData(int index) {
return (E) elementData[index];
}
public E set(int index, E element)
用指定的元素替换此列表中指定位置的元素。
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
public boolean add(E e)
将指定的元素追加到此列表的末尾
public boolean add(E e) {
//扩大容量,修改modcount
ensureCapacityInternal(size + 1); // Increments modCount!!
//数组是从0开始的存元素的,而数组个数是从1开始计数的
//这里是往第size个位置上存元素
//再将元素个数加1
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
//计算数组容量
private static int calculateCapacity(Object[] elementData, int minCapacity) {
//如果elementData为空,则设置容量大小为 Math.max(DEFAULT_CAPACITY, minCapacity);
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
public void add(int index,E element)
将指定元素插入此列表中的指定位置。 将当前位于该位置的元素(如果有)和后续元素向右移动。
public void add(int index, E element) {
//下标检查,是否越界了
rangeCheckForAdd(index);
//扩增容量,同时改变modcount
ensureCapacityInternal(size + 1); // Increments modCount!!
//index后面的元素后移
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
//指定位置放置元素
elementData[index] = element;
//元素数量大小自增
size++;
}
public E remove(int index)
删除此列表中指定位置的元素。 将任何后续元素向左移动)。
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;
}
public boolean remove(Object o)
从此列表中删除指定元素的第一个匹配项(如果存在)。 如果列表不包含该元素,则不会更改。
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
// 遍历ArrayList,找到元素o,删除并返回true。
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
//快速删除第index个元素并且不返回删除的值。
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
}
public void clear()
从此列表中删除所有元素。 此调用返回后,列表将为空。
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
public boolean addAll(Collection<? extends E> 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)
从指定位置开始,将指定集合中的所有元素插入此列表。 将当前位置的元素(如果有)和后续元素向右移动。 新元素将按照指定集合的迭代器返回的顺序出现在列表中。
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;
}
protected void removeRange(int fromIndex,int toIndex)
从此列表中删除索引介于fromIndex(包含)和 toIndex(不包含)之间的所有元素。 将任何后续元素向左移动, 此调用通过(toIndex - fromIndex)元素缩短列表。如果toIndex == fromIndex,则此操作无效。
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;
}
public boolean removeAll(Collection<?> c)
从此列表中删除指定集合中包含的所有元素。
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(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)
elementData[w++] = elementData[r];
} finally {
// 保留与AbstractCollection的行为兼容性,即使c.contains()抛出异常。
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;
}
public boolean retainAll(Collection<?> c)
从该列表中删除未包含在指定集合中的所有元素。
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
public ListIterator listIterator(int index)
从列表中的指定位置开始,返回列表中元素的列表迭代器。 指定的索引指示初始调用next时将返回的第一个元素。 对previous的初始调用将返回指定索引减去1的元素。
public ListIterator<E> listIterator(int index) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: "+index);
return new ListItr(index);
}
//AbstractList.ListItr 的优化版本
private class ListItr extends 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;
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();
}
}
}
public ListIterator listIterator()
返回此列表中元素的列表迭代器(按适当顺序)。
public ListIterator<E> listIterator() {
return new ListItr(0);
}
public Iterator iterator()
以适当的顺序返回此列表中元素的迭代器。
public Iterator<E> iterator() {
return new Itr();
}
//AbstractList.Itr 的优化版本
private class Itr implements Iterator<E> {
int cursor; // 要返回的下一个元素的索引
int lastRet = -1; // 返回最后一个元素的索引; 如果没有返回 -1
int expectedModCount = modCount;
Itr() {}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
//元素下标 >=size ,不存在对应位置的元素
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
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();
}
}
@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++]);
}
// 在迭代结束时更新一次以减少堆写入流量
cursor = i;
lastRet = i - 1;
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
ArrayList方法总结
- ArrayList 实际上是通过一个数组去保存数据的。当我们构造ArrayList时;若使用默认构造函数,则ArrayList的默认容量大小是10。
- 当ArrayList容量不足以容纳全部元素时,ArrayList会重新设置容量:新的容量=原有容量+(原有容量/2)。
- ArrayList的克隆函数,即是将全部元素克隆到一个数组中。
- ArrayList实现java.io.Serializable的方式。当写入到输出流时,先写入“容量”,再依次写入“每一个元素”;当读出输入流时,先读取“容量”,再依次读取“每一个元素”。
- ArrayList基于数组实现,可以通过下标索引直接查找到指定位置的元素,因此查找效率高,但每次插入或删除元素,就要大量地移动元素,插入删除元素的效率低。
- 在查找给定元素索引值等的方法中,源码都将该元素的值分为null和不为null两种情况处理,ArrayList中允许元素为null。
ArrayList遍历方式
通过迭代器遍历
List<String> list = new ArrayList<>();
Iterator iter = list.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}
通过索引遍历
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
for循环遍历
for (String s:list){
System.out.println(s);
}
ArrayList扩容策略
ArrayList底层是使用数组存储的,当数组大小不足存放新增元素的时候,才会发生扩容。
在add操作中,ArrayList首先会调用ensureCapacityInternal方法进行扩容检测的。
如果数组大小不足,则会自动扩容;如果扩容后的大小超出数组最大的大小,则会抛出异常。
ArrayList扩容策略,主要有两个步骤:
- 扩容检测(ensureCapacityInternal(size + 1)):
检测数组大小是否为0,如果是,则使用默认的扩容大小10
检测是否需要扩容,只有当数组期望容量大于当前数组大小时,才会进行扩容
- 扩容操作 grow和hugeCapacity
进行数组越界判断
拷贝原始数据到新的数组中
//扩容检测
private static int calculateCapacity(Object[] elementData, int minCapacity) {
// 如果底层数组大小为0,则使用默认的容量大小10
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
// 数据结构发生改变,和fail-fast机制有关,在使用迭代器过程中,只能通过迭代器的方法(比如迭代器中add,remove等),修改List的数据结构,
// 如果使用List的方法(比如List中的add,remove等),修改List的数据结构,会抛出ConcurrentModificationException
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// 当前数组容量大小不足时,才会调用grow方法,自动扩容
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
//扩容操作 grow和hugeCapacity
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
// 新的容量大小(即原容量1.5倍) = 原容量大小+(原容量大小/2)
int newCapacity = oldCapacity + (oldCapacity >> 1);
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;
}
上述若有不对,希望指正,一起学习,一起进步。