ArrayList简介
ArrayList简介
ArrayList以数组为底层数据结构的集合,是一个动态的数组队列,就是说该类的容量可以增长,与一般的数组不同。
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
可以看出Arraylist其继承AbstractList抽象类,而AbstractList也实现了 List接口。
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E>
实现的接口:
List:表示该集合可以存储重复的元素,具有增删改查的功能。
RandomAccess:表明给类有随机访问元素的功能(数组下标实现)。
Cloneable:表明可以在堆中可以克隆出与对象一样的对象,并且两个对象地址都不一样,即对克隆出来的对象修改影响不了被克隆对象。
API接口
// Collection中定义的API
boolean add(E object)
boolean addAll(Collection<? extends E> collection)
void clear()
boolean contains(Object object)
boolean containsAll(Collection<?> collection)
boolean equals(Object object)
int hashCode()
boolean isEmpty()
Iterator<E> iterator()
boolean remove(Object object)
boolean removeAll(Collection<?> collection)
boolean retainAll(Collection<?> collection)
int size()
<T> T[] toArray(T[] array)
Object[] toArray()
// AbstractCollection中定义的API
void add(int location, E object)
boolean addAll(int location, Collection<? extends E> collection)
E get(int location)
int indexOf(Object object)
int lastIndexOf(Object object)
ListIterator<E> listIterator(int location)
ListIterator<E> listIterator()
E remove(int location)
E set(int location, E object)
List<E> subList(int start, int end)
// ArrayList新增的API
Object clone()
void ensureCapacity(int minimumCapacity)
void trimToSize()
void removeRange(int fromIndex, int toIndex)
ArrayList的属性
// 序列化id
private static final long serialVersionUID =8683452581122892189L;
//默认容量
private static final int DEFAULT_CAPACITY = 10;
//当使用有参构造方法且参数为0时给elementData赋值空对象
private static final Object[] EMPTY_ELEMENTDATA = {};
//当使用无参构造方法时给elementData赋值空对象
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
//底层数据结构,数据对象存储地方
transient Object[] elementData;
//数组长度
private int size;
//数组最大长度
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
EMPTY_ELEMENTDATA与DEFAULTCAPACITY_EMPTY_ELEMENTDATA区别得结合构造方法及扩容函数才比较弄得清楚。
MAX_ARRAY_SIZE为什么不是Integer.MAX_VALUE而是Integer.MAX_VALUE-8呢,原因是数组需要8个字节存储数组长度。
ArrayList的构造方法
ArrayList的构造方法有三种。
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
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);
}
}
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,size=0,当一次添加元素时,回默认扩容到10。
int的有参构造方法:根据用户自定义的容量初始化,当容量为0时,回给数组赋值EMPTY_ELEMENTDATA空数组。
Collection的有参构造方法:先对Collection c进行toArray()转换为数组形式,若其数组长度不为0,还得对数组元素类型进行判断,不同就转换为Object。若数组长度为0就赋值EMPTY_ELEMENTDATA空数组。
ArrayList的add方法
add方法有4种(包括AbstractList里面的2种)
在ArrayList定义的2种及使用的相关函数:
//第一种(无索引的加入单个元素)
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
//第二种(有索引加入单个元素)
public void add(int index, E element) {
//判断索引是否有效
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1);
System.arraycopy(elementData, index, elementData, index + 1,
size - index);//将索引后的index都往后移一位
elementData[index] = element;//放入目标索引
size++;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
//判断容器内elementData是否第一次初始化,且使用无参构造函数初始化,若是,则返回初始容量10.
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
//判断是否需要扩容函数
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// 超出容量需要扩容
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
//扩容函数
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);//右移一位,相当于十进制除以2,则扩容的大小为原来的1.5倍
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);
}
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
通过上面的构造函数,我们可以就之前那个问题DEFAULTCAPACITY_EMPTY_ELEMENTDATA、EMPTY_ELEMENTDATA的区别 了, 通过无参构造函数进行构建的容器,调用calculateCapacity方法,minCapacity会变成10,而有参构造函数,参数为0的情况,调用calculateCapacity方法,minCapacity则还是为1(0+1),所以在扩容的时候,前者扩容为10,而后者扩容为1。这就是两个属性的区别。
还有两种add方法来自 AbstractList抽象类
//第三种(有索引的加入多个元素)
public boolean addAll(int index, Collection<? extends E> c) {
//检测下标是否正常
rangeCheckForAdd(index);
int cSize = c.size();
if (cSize==0)
return false;
//fast-fail机制检测
checkForComodification();
l.addAll(offset+index, c);
this.modCount = l.modCount;
size += cSize;
return true;
}
//第四种(无索引的加入多个元素)
public boolean addAll(Collection<? extends E> c) {
return addAll(size, c);
}
private void rangeCheckForAdd(int index) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private void checkForComodification() {
if (this.modCount != l.modCount)
throw new ConcurrentModificationException();
}
其实这两种的add方法跟前面两种没什么区别,这里就不做累述了,主要就是这里会抛出两个异常IndexOutOfBoundsException索引不正确与ConcurrentModificationException fail-fast失败这两个异常。
想了解fail-fast机制的:java中的fail-fast(快速失败)机制
ArrayList的remove方法
- remove(int index)
- remove(Object o)
- removeRange(int fromIndex, int toIndex)
- clear()
- removeAll(Collection c)
remove(int index)代码:
public E remove(int index) {
//检测索引是否正常
rangeCheck(index);
//fail-fast机制
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;
}
E elementData(int index) {
return (E) elementData[index];
}
remove(Object o)代码:
//大概思路就是遍历整个数组,找到该元素就删除掉。值得注意就是要分null与非null
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.
*这个注释的意思就是边界检查并不返回删除的值。
*这就是与第一个remove方法不同的地方。
*/
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
}
removeRange(int fromIndex, int toIndex)代码:
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;
}
删除部分元素,使用System.arraycopy覆盖就完成此功能。
clear()代码:
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
removeAll(Collection c)代码:
//从列表中移除指定 collection 中包含的其所有元素(可选操作)。
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)
//collection有的直接抛弃
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
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;
}
ArrayList查找方法
public E get(int index) {
//检查索引是否正常
rangeCheck(index);
return elementData(index);
}
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
//根据数组根据索引获取值
E elementData(int index) {
return (E) elementData[index];
}
ArrayList修改方法
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
基本跟上面没什么区别,就不太累述了。
ArrayList的trimToSize方法
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
该函数就是去掉数组没有使用的空间,就是(elementData.length在size索引 之后的空间。这里有一个就是特殊情况就是size。
ArrayList的toArray方法
ArrayList提供了一个将List转为数组的方法,该方法有两个重载,分别是
- Object[] toArray()
- toArray(T[] a)
**toArray() **代码:
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
toArray(T[] a)代码:
public <T> T[] toArray(T[] a) {
if (a.length < size)
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
第二个方法相对第一个方法可以要求数组类型,所以第一个方法容易抛出java.lang.ClassCastException错误。
例子:
ArrayList<String> list= new ArrayList<String>();
for(inti = 0 ; i < 10 ; i++) {
list.add( "" +i);
}
String[] array= (String[]) list.toArray();
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
at demo01.main(demo01.java:10)
ArrayList的indexOf与lastIndexOf方法
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;
}
//没找到会返回-1
return -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;
}
//没找到会返回-1
return -1;
}
最后:
ArrayList底层是有一个Object[]数组实现,具有实例化、随机访问访问、克隆的功能,其内部大量使用System.arraycopy 与Arrays.copyOf函数来实现它的功能。经过通过分析代码,ArrayList并不是并发安全,虽然其内部有fail-fast机制来保证,也就是有出现并发操作导致数据问题我就抛出问题出来,所以该类在并发下并不能使用。
补充
System.arraycopy与Arrays.copyOf区别
System.arraycopy代码:
public static native void arraycopy(Object src,int srcPos, Object dest, int destPos,int length);
/**
src:原数组
srcPos:原数数组起始位置
dest:目标数组
destPos:目标数组起始位置
length:要复制数组元素个数
该方法使用native,表示该方法是使用其他底层函数写的,相对来说更加高效。
*/
Arrays.copyOf代码:
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
@SuppressWarnings("unchecked")
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;
}
/**
original:要复制的数组
newLength:新数组的长度
newType:新数组的类型
*/
两个方法区别:
System.arraycopy是对目标数组来进行复制数据操作。
Arrays.copyOf是内部创建一个数组再进行复制操作,其内部也是需要调用System.arraycopy来进行操作。
深入学习System.arraycopy:《System.arraycopy为什么快》
ArrayList简介的更多相关文章
- Java集合源码分析(二)ArrayList
ArrayList简介 ArrayList是基于数组实现的,是一个动态数组,其容量能自动增长,类似于C语言中的动态申请内存,动态增长内存. ArrayList不是线程安全的,只能用在单线程环境下,多线 ...
- Java 集合系列03之 ArrayList详细介绍(源码解析)和使用示例
概要 上一章,我们学习了Collection的架构.这一章开始,我们对Collection的具体实现类进行讲解:首先,讲解List,而List中ArrayList又最为常用.因此,本章我们讲解Arra ...
- Java 集合系列 03 ArrayList详细介绍(源码解析)和使用示例
java 集合系列目录: Java 集合系列 01 总体框架 Java 集合系列 02 Collection架构 Java 集合系列 03 ArrayList详细介绍(源码解析)和使用示例 Java ...
- 【ITOO 2】使用ArrayList时的注意事项:去除多余的null值
问题描述:在课表导入的时候,将数据从excel表里读出,然后将list批量插入到对应的课程表的数据表单中去,出现结果:当我们导入3条数据时,list.size()为3,但是实际上,list里面存在10 ...
- ArrayList源代码深入剖析
第1部分 ArrayList介绍ArrayList底层采用数组实现,它的容量能动态增长.它继承于AbstractList,实现了List, RandomAccess, Cloneable, java. ...
- ArrayList源码解析
ArrayList简介 ArrayList定义 1 public class ArrayList<E> extends AbstractList<E> implements L ...
- 【转】Java 集合系列03之 ArrayList详细介绍(源码解析)和使用示例
原文网址:http://www.cnblogs.com/skywang12345/p/3308556.html 上一章,我们学习了Collection的架构.这一章开始,我们对Collection的具 ...
- ArrayList源码剖析
ArrayList简介 ArrayList是基于数组实现的,是一个动态数组,其容量能自动增长,类似于C语言中的动态申请内存,动态增长内存. ArrayList不是线程安全的,只能用在单线程环境下,多线 ...
- 转:【Java集合源码剖析】ArrayList源码剖析
转载请注明出处:http://blog.csdn.net/ns_code/article/details/35568011 本篇博文参加了CSDN博文大赛,如果您觉得这篇博文不错,希望您能帮我投一 ...
随机推荐
- RxJava2源码解析(二)
title: RxJava2源码解析(二) categories: 源码解析 tags: 源码解析 rxJava2 前言 本篇主要解析RxJava的线程切换的原理实现 subscribeOn 首先, ...
- CF思维联系– Codeforces-990C Bracket Sequences Concatenation Problem(括号匹配+模拟)
ACM思维题训练集合 A bracket sequence is a string containing only characters "(" and ")" ...
- 数学--数论--Alice and Bob (CodeForces - 346A )推导
It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. ...
- Java集合面试题汇总篇
文章收录在 GitHub JavaKeeper ,N线互联网开发必备技能兵器谱 作为一位小菜 "一面面试官",面试过程中,我肯定会问 Java 集合的内容,同时作为求职者,也肯定会 ...
- LateX公式表
转载自xkgjfl 话说为什么LateX公式这么难记 markdown最全数学公式 我们在用markdown写文档时有时候少不了需要插入一些公式,然而markdown公式输入远没有word这么直观,有 ...
- spring mvc从前台往后台传递参数的三种方式
jsp页面: 第一种:使用控制器方法形参的方式(常用) 第二种:使用模型传参的方式(如果前台往后台传递的参数非常多,如果还使用形参的方式传递,非常复杂.我们可以使用模型传参的方式,把多 个请求的参数 ...
- webpack搭建环境步骤
一.初始化 1.创建文件夹 2.npm init -y 二.安装webpack 和webpack-cli 1.yarn add webpack webpack-cli@3.3.10 -D (这里指定 ...
- Qt编程基础入门之二
QMainWindow 菜单栏 菜单栏 最多有一个 //菜单栏创建,一个 QMenuBar *menu = new QMenuBar(this); // this->setMenuBar(men ...
- blesta运行造成阿里云服务器CPU频繁超载的原因分析
博主在阿里云服务器上安装了主机软件Blesta后,阿里云后台频繁提示CPU超载,打开突发性能模式后,发现CPU负载到了100%.如下图所示: 直接在putty里面reboot整个系统后,负载瞬间降为2 ...
- 【FPGA篇章五】FPGA函数任务:对讲解函数与任务专题展开详解
欢迎大家关注我的微信公众账号,支持程序媛写出更多优秀的文章 任务和函数也属于过程块,多用于仿真文件设计中,使用两者的目的有所区别: 函数(function):对输入的值执行一些处理,返回一个新的值. ...