一、简介
1.继承的父类 & 实现的接口
继承了 抽象类AbstractList,
实现了 List, RandomAccess, Cloneable, java.io.Serializable 接口
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
2.底层结构
ArrayList 底层是通过数组实现的。
特点是: 元素 有序 可重复,
适用于遍历或修改,增删时效率较慢。
3.基本方法
1.增(add)、删(remove)、改(set)、查(get)
2.交(retainAll):保留两个集合相同的部分。
3.并(addAll): 合并两个集合的所有元素,包括重复元素。
4.差(removeAll):保留比形参多的部分
二、构造方法的调用
1.无参构造
List arrayList = new ArrayList<>();
//由 DEFAULT_CAPACITY = 10 确定,默认创建的数组长度为10。
2.有参构造
List arrayList = new ArrayList<>(5);
//根据自己的需求,创建了一个长度为5数组。
3.利用集合构造集合
HashSet hashSet = new HashSet();
List arrayList = new ArrayList<>(hashSet);
//利用同为Collection接口下的其他集合构建ArrayList集合,以实现集合之间的相互转换。
三、源码分析
1.重要属性
/**
* serialVersionUID:序列化的版本号
*/
private static final long serialVersionUID = 8683452581122892189L;
/**
* 默认初始容量:默认数组长度为10
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* 用于空实例的共享空数组实例
* EMPTY_ELEMENTDATA:空元素数据
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* 共享的空数组实例用于默认大小的空实例。
* 我们将其与 EMPTY_ELEMENTDATA 区分开来,
* 以便知道当添加第一个元素时膨胀多少。
* DEFAULTCAPACITY_EMPTY_ELEMENTDATA:空元素数据的默认容量
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* 数组列表中存储元素的数组缓冲区。
* 数组列表的容量就是这个数组缓冲区的长度。
*/
transient Object[] elementData;
/**
* 数组列表的大小(容纳元素的数量)。
*/
private int size;
/**
* 要分配的数组的最大大小。
* 有些虚拟机在数组中保留一些头词。
* 尝试分配更大的数组可能导致
* OutOfMemoryError(堆溢出错误):请求的数组大小超过虚拟机限制
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
2.重要方法
1>.构造方法
无参构造
/**
* Constructs an empty list with an initial capacity of ten.
*
* 构造一个初始容量为10的空列表。
*
* 调用此无参构造,
* 底层会把数组DEFAULTCAPACITY_EMPTY_ELEMENTDATA赋给elementData对象。
*
*
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
有参构造
/**
* Constructs an empty list with the specified initial capacity.
*
* 构造一个具有指定初始容量的空列表,
* 数组长度为 initialCapacity 。
*
* @param initialCapacity the initial capacity of the list
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
public ArrayList(int initialCapacity) {
//如果长度>0,就将elementData构造成一个 initialCapacity长度的数组
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
}
//如果长度=0,就把 空数组EMPTY_ELEMENTDATA 的地址引用赋给 elementData对象
else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
}
//数组长度<0时,抛出 IllegalArgumentException(非法参数异常)
else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
利用集合构造集合
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* 构造包含指定元素的列表集合,
* 按它们被集合迭代器返回的顺序构建。
*
* 利用同为Collection接口下的其他集合构建ArrayList集合,以实现集合之间的相互转换。
*
* @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) {
//将形参c通过toArray方法转化为Object[]数组,同时将里面的数据复制过来
elementData = c.toArray();
//如果形参数组的长度不为0
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
// 检查数据类型:c.toArray可能(不正确地)不返回Object[]
if (elementData.getClass() != Object[].class)
//复制成长度为size的 Object[]类型
elementData = Arrays.copyOf(elementData, size, Object[].class);
}
//如果长度为0
else {
// replace with empty array.
// 用空数组替换
this.elementData = EMPTY_ELEMENTDATA;
}
}
2>.扩容方法
/**
* Increases the capacity of this <tt>ArrayList</tt> instance, if
* necessary, to ensure that it can hold at least the number of elements
* specified by the minimum capacity argument.
*
* 增加ArrayList实例的容量,
* 以确保它能容纳至少由 最小容量参数minCapacity 指定的元素数量。
*
* @param minCapacity the desired minimum capacity
*/
public void ensureCapacity(int minCapacity) {
// 如果elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA,即当前对象不是通过无参构造方法创建的,
// 让 minExpand = 0;这里赋值为0是个标记,
// 保证下面的 if (minCapacity > minExpand)一定成立,此时一定要去判断一下是否需要扩容。
// 否则表示,当前对象是通过无参构造方法创建的(此时容量为0),
// 则让 minExpand = DEFAULT_CAPACITY = 10。
int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
// any size if not default element table(如果不是默认元素表的任何大小)
? 0
// larger than default for default empty table. It's already
// supposed to be at default size.(大于默认空表的默认值。它已经被默认大小。)
: DEFAULT_CAPACITY;
//如果 所需的最小容量 > minExpand
if (minCapacity > minExpand) {
//根据minCapacity判断 ,是否需要执行扩容操作
ensureExplicitCapacity(minCapacity);
}
}
private void ensureCapacityInternal(int minCapacity) {
//如果elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA,即当前对象是通过无参构造方法创建的
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
//所需最小容量minCapacity, 需要更新为较大的那个值
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
//根据minCapacity判断 ,是否需要执行扩容操作
ensureExplicitCapacity(minCapacity);
}
//此方法只是用于判断,是否需要扩容
//真正执行扩容操作的是里面的grow(minCapacity)函数
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
//如果 所需最小容量>底层数组的实际长度
if (minCapacity - elementData.length > 0)
//执行扩容操作
grow(minCapacity);
}
/**
* The maximum size of array to allocate.
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
*
* 要分配的数组的最大大小。
* 有些虚拟机在数组中保留一些字头。
* 尝试分配更大的数组可能导致
* OutOfMemoryError(堆溢出错误):请求的数组大小超过虚拟机限制
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
*
* 增加容量,以确保它能容纳至少由 最小容量参数minCapacity 指定的元素数量。
*
*
*
* @param minCapacity the desired minimum capacity
*/
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
//新数组的容量为 原数组的1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
//如果原数组的1.5倍还是不够,则更新为所需的最小容量
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:
//扩容 + 搬家
//首先创建一个newCapacity长度的数组,把elementData的原有内容复制过去,
//再把新的地址引用传回来,赋值给 elementData
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;
}
3.常用方法
1>.基本方法
1.增加 add()
add(E e)方法:
/**
* 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,判断一下是否需要扩容
ensureCapacityInternal(size + 1); // Increments modCount!!
//至此,数组容量一定够用,此时将新元素追加到列表的末尾。
elementData[size++] = e;
return true;
}
add(int index, E element)方法:
/**
* 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).
*
* 将指定元素插入到列表的指定位置。
* 将当前在该位置的元素(如果有的话)以及 后续的所有元素向右移动(在其下标上加1)。
*
* @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);
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
2.删除 remove()
remove(int index)方法:
/**
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*
* 删除:移除列表中指定索引处的元素。
* 将所有后续元素向左移动(在其下标上-1),
* 有效元素个数-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);
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;
}
remove(Object o)方法:
/**
* 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
*/
public boolean remove(Object o) {
//此函数只负责在列表中寻找指定元素第一次出现的位置,
//真正执行删除操作的是里面的fastRemove(index)函数。
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.
*
* 私有的删除方法,跳过边界检查而不做。
* 将集合的有效元素个数-1,返回已删除的值。
*/
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
}
3.修改set()
set(int index, E element)方法:
/**
* 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;
}
//根据索引index,返回数组对应位置处的元素值
// Positional Access Operations
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
4.查找 get()
get(int index)方法:
/**
* 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);
}
2>.常用方法
1.clone()方法:
/**
* Returns a shallow copy of this <tt>ArrayList</tt> instance.
* (The elements themselves are not copied.)
*
* 返回这个ArrayList实例的浅拷贝。
* (元素本身不会被复制。)
*
* 浅拷贝:只是将当前对象的地址引用指向了目标对象,
* 元素本身并没有进行复制,当前对象会因为目标对象内容的改变而同步的发生改变(因为地址引用是一样的)。
*
* 想要实现元素本身的复制,可借助循环,一一遍历,一一复制。
*
* @return a clone of this <tt>ArrayList</tt> instance
*/
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);
}
}
2.toArray()方法:
/**
* Returns an array containing all of the elements in this list
* in proper sequence (from first to last element).
*
* 返回包含列表中所有元素的数组
* 按适当的顺序(从第一到最后一个元素)。
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this list. (In other words, this method must allocate
* a new array). The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this list in
* proper sequence
*/
public Object[] toArray() {
//返回一个size长度,包括elementData所有元素的 Object型数组。
return Arrays.copyOf(elementData, size);
}
/**
* Returns an array containing all of the elements in this list in proper
* sequence (from first to last element); the runtime type of the returned
* array is that of the specified array. If the list fits in the
* specified array, it is returned therein. Otherwise, a new array is
* allocated with the runtime type of the specified array and the size of
* this list.
*
* <p>If the list fits in the specified array with room to spare
* (i.e., the array has more elements than the list), the element in
* the array immediately following the end of the collection is set to
* <tt>null</tt>. (This is useful in determining the length of the
* list <i>only</i> if the caller knows that the list does not contain
* any null elements.)
*
* @param a the array into which the elements of the list are to
* be stored, if it is big enough; otherwise, a new array of the
* same runtime type is allocated for this purpose.
* @return an array containing the elements of the list
* @throws ArrayStoreException if the runtime type of the specified array
* is not a supertype of the runtime type of every element in
* this list
* @throws NullPointerException if the specified array is null
*/
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
3.trimToSize()方法:
/**
* Trims the capacity of this <tt>ArrayList</tt> instance to be the
* list's current size. An application can use this operation to minimize
* the storage of an <tt>ArrayList</tt> instance.
*
* 将ArrayList实例的容量修剪为列表的当前大小。
* 应用程序可以使用此操作来最小化存储ArrayList实例。
*
* 将没有存储有效数据的部分裁剪掉,
* 得到的数组长度(elementData.length) = 有效数据的个数(size)
*/
public void trimToSize() {
modCount++;
if (size < elementData.length) {
//如果size == 0,则 elementData = EMPTY_ELEMENTDATA;
//否则,将裁掉无效元素后的数组赋给 elementData。
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
4.clear()方法:
/**
* Removes all of the elements from this list. The list will
* be empty after this call returns.
*
* 从列表中删除所有元素。
* 此方法调用返回后,有效元素个数记为0,列表将为空。
*/
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
5.isEmpty()方法:
/**
* Returns <tt>true</tt> if this list contains no elements.
*
* 判断数组是否为空,如果数组内没有元素则返回true。
*
* @return <tt>true</tt> if this list contains no elements
*/
public boolean isEmpty() {
return size == 0;
}
6.contains(Object o)方法:
/**
* Returns <tt>true</tt> if this list contains the specified element.
* More formally, returns <tt>true</tt> if and only if this list contains
* at least one element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.
*
* 如果集合中存在此元素,则返回true
*
* @param o element whose presence in this list is to be tested
* @return <tt>true</tt> if this list contains the specified element
*/
public boolean contains(Object o) {
//如果indexOf(o) >= 0,表示元素0存在
return indexOf(o) >= 0;
}
7.indexOf(Object o)和lastIndexOf(Object o)方法:
/**
* 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
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*
* 返回指定元素第一次出现的索引下标,
* 如果列表中不包含该元素,则为-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;
}
/**
* 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
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*
* 返回指定元素最后一次出现的索引下标,
* 如果列表中不包含该元素,则为-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;
}