ArrayList 是一个数组队列,相当于 动态数组。与Java中的数组相比,它的容量能动态增长。
ArrayList继承于AbstractList,实现了List, RandomAccess, Cloneable, java.io.Serializable这些接口。如下图:
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
扩展:ArrayList和Vector不同,ArrayList中的操作不是线程安全的!所以,建议在单线程中才使用ArrayList,而在多线程中可以选择Vector。
private static final long serialVersionUID = 8683452581122892189L;
/**
* Default initial capacity.
* 默认初始化容量
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* Shared empty array instance used for empty instances.
* 空数组,当用户创建空实例时,返回该数组
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.
* 空数组实例
* - 当用户没有指定 ArrayList 的容量时(即调用无参构造函数),返回的是该数组==>刚创建一个 ArrayList 时,其内数据量为 0。
* - 当用户第一次添加元素时,该数组将会扩容,变成默认容量为 10(DEFAULT_CAPACITY) 的一个数组===>通过 ensureCapacityInternal() 实现
*/
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 关键字最主要的作用就是当序列化时,被transient修饰的内容将不会被序列化
*/
transient Object[] elementData; // non-private to simplify nested class access
/**
* The size of the ArrayList (the number of elements it contains).
* 数组中的元素个数
* @serial
*/
private int size;
/**
* 这个列表在结构上被修改的次数。结构修改是指改变列表的大小,或者以一种正在进行的迭代可能会保留不正确结果的方式扰乱列表。
*/
protected transient int modCount = 0;
提示:size和elementData.length是不相同的。size是指当前集合中存在的元素个数,elementData.length是指当前集合指定的容量大小例如,如果我们ArrayList()时,ArrayList只是给我们默认的elementData=DEFAULTCAPACITY_EMPTY_ELEMENTDATA,此时只是空数组,只有第一次add时才默认数组的大小为DEFAULT_CAPACITY=10 ,此时elementData.length=10,而size=0
构造一个指定容量的ArrayList。这是一个带初始容量大小的有参构造函数。
/**
* Constructs an empty list with the specified initial capacity.
* - 构造一个指定容量的ArrayList。这是一个带初始容量大小的有参构造函数。
* @param initialCapacity the initial capacity of the list
* - 初始化容量
* @throws IllegalArgumentException if the specified initial capacity
* is negative
* - 如果指定的初始容量为负,抛出异常
*/
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对象的时候不传入参数,则使用此无参构造方法创建ArrayList对象。从前面知道DEFAULTCAPACITY_EMPTY_ELEMENTDATA是一个空的Object[],给到elementData进行初始化,elementData也是个Object[]类型。当有元素进行第一次添加 add() 时,elementData将会变成默认的长度10。
/**
* Constructs an empty list with an initial capacity of ten.
* - 无参构造方法,创建ArrayList对象的时候不传入参数,则使用此无参构造方法创建ArrayList对象
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
注意:默认容量为10,调用无参构造此时的容量0,当第一次调用 add() 方法时才进行扩容为10。
构造一个包含指定 collection 的元素的列表,这些元素是按照该 collection 的迭代器返回它们的顺序排列的。
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
* - 构造一个包含指定 collection 的元素的列表,这些元素是按照该 collection 的迭代器返回它们的顺序排列的。
* @param c the collection whose elements are to be placed into this list
* - 放入此列表的集合
* @throws NullPointerException if the specified collection is null
* - 如果集合为空,抛出异常
*/
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)
// copyOf(要复制的数组,要返回的副本的长度,要返回的副本的类)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
// 将空数组 EMPTY_ELEMENTDATA 赋值给 elementData。
this.elementData = EMPTY_ELEMENTDATA;
}
}
总结:ArrayList 构造方法就是初始化存储数据容器。存储数据容器其本质就是数组,在ArrayList中叫elementData。
将指定的元素添加此集合的末尾。
/**
* Appends the specified element to the end of this list.
* - 将指定的元素添加此集合的末尾。
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
public boolean add(E e) {
// 检查数组容量,不够,容器+1,
// 注意:只+1,因为add()一次只添加一个元素,并且也能确保资源不被浪费。
ensureCapacityInternal(size + 1); // Increments modCount!!
//添加对象,自增size 等同于 elementData[size]; size++;
elementData[size++] = e;
return true;
}
// 检查数组容量,不够扩容。
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
//若 elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA 则取 DEFAULT_CAPACITY 和 minCapacity 的最大值
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
// 检查数组容量,不够扩容。
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
//最小容量 > 数组长度 = 扩容
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
/**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
* - 数组扩容,以确保它至少可以容纳由最小容量参数指定的元素数量。
* @param minCapacity the desired minimum capacity
*/
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
// >>:表示右移,如果该数为正,则高位补0,若为负数,则高位补1
// eg : 10 的二进制(1010) 右移 变成 0101(十进制5),所以扩容是1.5倍
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:
// 拷贝数组,改变容量大小。
// Arrays.copyof(原数组,新的数组长度)
elementData = Arrays.copyOf(elementData, newCapacity);
}
// 进行大容量分配
private static int hugeCapacity(int minCapacity) {
// 如果minCapacity<0,抛出异常
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
// 如果想要的容量大于MAX_ARRAY_SIZE,则分配Integer.MAX_VALUE,否则分配MAX_ARRAY_SIZE
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
指定元素插入到列表中的指定位置。
/**
* Inserts the specified element at the specified position in this
* list. Shifts the element currently at that position (if any) and
* any subsequent elements to the right (adds one to their indices).
* - 将指定元素插入到列表中的指定位置。将当前位于该位置的元素(如果有)和任何后续元素向右移动(将一个元素添加到它们的索引中)。
* @param index index at which the specified element is to be inserted
* - 要插入指定元素的索引
* @param element element to be inserted
* - 要插入的元素
* @throws IndexOutOfBoundsException {@inheritDoc}
* - 抛出异常
*/
public void add(int index, E element) {
// 检查索引是否越界
rangeCheckForAdd(index);
// 检查数组容量,不够,扩容
// 注意:只+1,因为add()一次只添加一个元素,并且也能确保资源不被浪费。
ensureCapacityInternal(size + 1); // Increments modCount!!
// System.arraycopy(源数组,源数组起始索引,目标数组,目标数组起始索引,要拷贝的长度)
// 主要思想:将当前位于该位置的元素(如果有)和任何后续元素向右移动(将一个元素添加到它们的索引中)。
System.arraycopy(elementData, index, elementData, index + 1, size - index);
// 指定索引位置赋值
elementData[index] = element;
// 大小+1
size++;
}
/**
* A version of rangeCheck used by add and addAll.
*/
private void rangeCheckForAdd(int index) {
//要插入的索引位置不能小于0,不能大于size
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
总结:add(int index, E element)先检查索引是否越界,再判断是否需要扩容,再将需要右移的元素右移,最后赋值,修改大小。
删除列表中指定位置的元素。将后续所有元素向左移动(从它们的索引中减去1)。
/**
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
* - 删除列表中指定位置的元素。将后续所有元素向左移动(从它们的索引中减去1)。
* @param index the index of the element to be removed
* - 指定要删除的索引
* @return the element that was removed from the list
* - 删除的元素
* @throws IndexOutOfBoundsException {@inheritDoc}
* - 抛出异常
*/
public E remove(int index) {
// 检查索引是否越界
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
// 主要思想:
// - 1. 先计算出需要左移的元素长度
// - 2. 将后续所有元素向左移动(从它们的索引中减去1)。
int numMoved = size - index - 1;
if (numMoved > 0)
// System.arraycopy(源数组,源数组起始索引,目标数组,目标数组起始索引,要拷贝的长度)
System.arraycopy(elementData, index+1, elementData, index, numMoved);
// 左移后,将最后一个元素至空
elementData[--size] = null; // clear to let GC do its work
// 返回删除的元素值
return oldValue;
}
/**
* Checks if the given index is in range. If not, throws an appropriate
* runtime exception. This method does *not* check if the index is
* negative: It is always used immediately prior to an array access,
* which throws an ArrayIndexOutOfBoundsException if index is negative.
* - 检查给定的索引是否在范围内。如果不是,则抛出适当的运行时异常。该方法不*not*检查索引是否为负数:它总是在数组访问之前使用,如果索引为负数,则会抛出ArrayIndexOutOfBoundsException。
*/
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* Constructs an IndexOutOfBoundsException detail message.
* Of the many possible refactorings of the error handling code,
* this "outlining" performs best with both server and client VMs.
* - 构造一个角标越界提示信息
*/
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
//获取指定索引的值
E elementData(int index) {
return (E) elementData[index];
}
总结:remove(int index)先检查索引是否越界,然后计算出要左移的元素长度,最后左移。将最后一个元素至空。
从该列表中删除指定元素的第一个匹配项(如果存在)。如果列表不包含该元素,它将保持不变。确切的说,删除索引最小的元素
/**
* Removes the first occurrence of the specified element from this list,
* if it is present. If the list does not contain the element, it is
* unchanged. More formally, removes the element with the lowest index
* - 从该列表中删除指定元素的第一个匹配项(如果存在)。如果列表不包含该元素,它将保持不变。确切的说,删除索引最小的元素
* <tt>i</tt> such that
* <tt>(o==null ? get(i) == null : o.equals(get(i)))</tt>
* (if such an element exists). Returns <tt>true</tt> if this list
* contained the specified element (or equivalently, if this list
* changed as a result of the call).
*
* @param o element to be removed from this list, if present
* - 要删除的对象
* @return <tt>true</tt> if this list contained the specified element
* - 返回true or false
*/
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 remove method that skips bounds checking and does not
* return the value removed.
* - 私有移除方法,该方法跳过边界检查且不返回被移除的值。
*/
private void fastRemove(int index) {
modCount++;
// 计算要左移元素的长度
int numMoved = size - index - 1;
if (numMoved > 0)
// System.arraycopy(源数组,源数组起始索引,目标数组,目标数组起始索引,要拷贝的长度)
System.arraycopy(elementData, index+1, elementData, index, numMoved);
// 左移后,将最后一个元素至空
elementData[--size] = null; // clear to let GC do its work
}
总结:remove(Object o):删除指定元素,不用检查索引越界。此方法只删除索引值最小的元素。
返回列表中指定位置的元素。
/**
* Returns the element at the specified position in this list.
* - 返回列表中指定位置的元素。
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
// 检查索引是否越界
rangeCheck(index);
// 获取指定索引上的元素
return elementData(index);
}
将列表中指定位置的元素替换为指定元素。
/**
* Replaces the element at the specified position in this list with
* the specified element.
* - 将列表中指定位置的元素替换为指定元素。
* @param index index of the element to replace
* - 要替换的元素的索引
* @param element element to be stored at the specified position
* - 元素存储在指定位置
* @return the element previously at the specified position
* - 先前位于指定位置的元素
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E set(int index, E element) {
// 检查索引越界
rangeCheck(index);
// 获取指定位置的元素
E oldValue = elementData(index);
// 替换指定位置的元素
elementData[index] = element;
// 返回被替换的元素
return oldValue;
}
返回该列表中指定元素第一次出现的索引,如果该列表不包含该元素,则返回-1。确切的说,返回最低的索引的元素
/**
* Returns the index of the first occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the lowest index <tt>i</tt> such that
* - 返回该列表中指定元素第一次出现的索引,如果该列表不包含该元素,则返回-1。确切的说,返回最低的索引的元素
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*/
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;
}
返回指定元素最后一次出现的索引,如果该列表不包含该元素,则返回-1。确切的说,返回最高的索引的元素
/**
* Returns the index of the last occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the highest index <tt>i</tt> such that
* - 返回指定元素最后一次出现的索引,如果该列表不包含该元素,则返回-1。确切的说,返回最高的索引的元素
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*/
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;
}
从列表中删除所有元素。该调用返回后,列表将为空。
/**
* Removes all of the elements from this list. The list will
* be empty after this call returns.
* - 从列表中删除所有元素。该调用返回后,列表将为空。
*/
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有