ArrayList 源码分析
介绍
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 继承了AbstractList,实现了List。AbstractList、List提供了相关的添加、删除、修改、遍历等功能。
- ArrayList 实现了RandmoAccess接口,即提供了随机访问功能。在ArrayList中,我们即可以通过元素的序号快速获取元素对象,这就是快速随机访问。
- ArrayList 实现了Cloneable接口,实现clone(),实现克隆。
- ArrayList 实现java.io.Serializable接口,意味着ArrayList支持序列化,能通过序列化去传输。
扩展: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提供了三种构造方法:
ArrayList(int initialCapacity)
构造一个指定容量的ArrayList。这是一个带初始容量大小的有参构造函数。
- 初始容量>0:返回指定容量的大小
- 初始容量=0:返回空数组
- 初始容量<0:抛出异常 IllegalArgumentException
/**
* 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对象的时候不传入参数,则使用此无参构造方法创建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。
ArrayList(Collection<? extends E> c)
构造一个包含指定 collection 的元素的列表,这些元素是按照该 collection 的迭代器返回它们的顺序排列的。
- 将 Collection 对象转换成数组并赋值给 elementData。
- 判断数组大小是否等于0,将空数组 EMPTY_ELEMENTDATA 赋值给 elementData。
- 如果size的值大于0,则执行Arrays.copy方法,把collection对象的内容(可以理解为深拷贝)拷贝到elementData中。
/**
* 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。
普通方法
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,
// 注意:只+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;
}
- 第一次调用add方法流程分析
- 调用 add() ,此时 size=0 ,size+1=1;
- 调用 ensureCapacityInternal(minCapacity) ,此时 minCapacity=1;
- 调用 calculateCapacity(elementData,minCapacity) ,此时 minCapacity=1 ,elementData={}, DEFAULT_CAPACITY=10 ,DEFAULTCAPACITY_EMPTY_ELEMENTDATA={};
- 因为 elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA 所以取 DEFAULT_CAPACITY ,minCapacity两数最大值 DEFAULT_CAPACITY;
- 返回 ensureCapacityInternal后,调用 ensureExplicitCapacity(minCapacity) ,此时 minCapacity=10, elementData.length=0;
- 因为 minCapacity - elementData.length > 0调用 grow();
- 先扩容 newCapacity = newCapacity + ( newCapacity >> 1 ),判断 newCapacity - minCapacity < 0,所以 newCapacity = minCapacity = 10;
- 拷贝数组,改变容量大小;
- 一并返回到 add(),添加对象,自增size;
- 第二次扩容:第二次扩容是指当前集合中已经存在10(默认容量10)个元素后,继续添加第11个元素。
- 调用 add() ,此时 size=10 ,size+1=11;
- 调用 ensureCapacityInternal(minCapacity) ,此时 minCapacity=11;
- 调用 calculateCapacity(elementData,minCapacity) ,此时 minCapacity=11 ,elementData.length=10, DEFAULT_CAPACITY=10 ,DEFAULTCAPACITY_EMPTY_ELEMENTDATA.length=0;
- 因为 elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA ,所以取 minCapacity=11;
- 返回 ensureCapacityInternal 后,调用 ensureExplicitCapacity(minCapacity) ,此时 minCapacity=11 ,elementData.length=10;
- 因为 minCapacity - elementData.length > 0 调用 grow();
- 先扩容 newCapacity = newCapacity + ( newCapacity >> 1 ) ,判断 newCapacity - minCapacity > 0,所以 newCapacity = newCapacity = 15;
- 拷贝数组,改变容量大小;
- 一并返回到add(),添加对象,自增size;
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).
* - 将指定元素插入到列表中的指定位置。将当前位于该位置的元素(如果有)和任何后续元素向右移动(将一个元素添加到它们的索引中)。
* @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)先检查索引是否越界,再判断是否需要扩容,再将需要右移的元素右移,最后赋值,修改大小。
remove
remove(int index)
删除列表中指定位置的元素。将后续所有元素向左移动(从它们的索引中减去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)先检查索引是否越界,然后计算出要左移的元素长度,最后左移。将最后一个元素至空。
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
* - 返回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):删除指定元素,不用检查索引越界。此方法只删除索引值最小的元素。
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);
}
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;
}
indexOf(Object o)
返回该列表中指定元素第一次出现的索引,如果该列表不包含该元素,则返回-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;
}
lastIndexOf(Object o)
返回指定元素最后一次出现的索引,如果该列表不包含该元素,则返回-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;
}
clear()
从列表中删除所有元素。该调用返回后,列表将为空。
/**
* 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;
}
- 记录安装oracle的那些事(四)之oracle 缺包安包
- 【面试虐菜】—— JAVA面试题(1)
- JAVA增删改查XML文件
- javascript去掉字符串前后空格
- 构建通用的 React 和 Node 应用
- 有趣的 CSS 像素艺术
- 【插件开发】—— 11 窃听风云(Java事件监听原理-GEF实例讲解)
- 【面试虐菜】—— JAVA面试题(2)
- JavaMelody监控spring、struts
- 《JavaScript语言精粹》—— 读书总结
- 视差滚动技术的简介及运用
- 【面试虐菜】—— JAVA面试题(3)
- Carousel 旋转画廊特效的疑难杂症
- 区块链为IBM与Visa等老牌公司注入新的生机
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- nginx系列:常用利用shell统计日志
- Nginx系列:图片过滤处理
- Nginx系列:几款负载均衡第三方插件的安装与使用
- 「高并发通信框架Netty4 源码解读(三)」NIO缓冲区Buffer详解
- UML类图符号:各种关系说明以及举例
- 「高并发通信框架Netty4 源码解读(四)」NIO缓冲区之字节缓冲区ByteBuffer详解
- 「influxDB 原理与实践(三)」连续查询
- 为什么使用OPA而不是原生的Pod安全策略?
- 浅入浅出 Java ConcurrentHashMap
- 「高并发通信框架Netty4 源码解读(五)」NIO通道Channel详解
- 图解一致性哈希算法,全网(小区局域网)最通俗易懂
- 「高并发通信框架Netty4 源码解读(六)」NIO通道之Socket通道
- 「高并发通信框架Netty4 源码解读(番外篇)」NIO实现大文件传输
- 「高并发通信框架Netty4 源码解读(七)」NIO通道之Selector选择器
- Python与seo工具脚本,360/搜狗相关搜索词采集源码参考