@ArrayList剖析
第1部分 ArrayList介绍
ArrayList简介
Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.) The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation. Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost. An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation. Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be "wrapped" using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list: List list = Collections.synchronizedList(new ArrayList(...)); The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.
ArrayList是一个动态数组容器类,会自动扩容。
以数组实现。节约空间,但数组有容量限制。超出限制时会增加50%容量(新容量是原来容量的1.5倍),用System.arraycopy()复制到新的数组,因此最好能给出数组大小的预估值(这个是好的编程习惯)。默认第一次插入元素时创建大小为10的数组。 按数组下标访问元素—get(i)/set(i,e) 的性能很高,这是数组的基本优势。 直接在数组末尾加入元素—add(e)的性能也高,但如果按下标插入、删除元素—add(i,e), remove(i), remove(e),则要用System.arraycopy()来移动部分受影响的元素,性能就变差了,这是基本劣势。
ArrayList中的操作不是线程安全的!在多线程中可以选择Vector或者CopyOnWriteArrayList。
来看一段简单的代码:
public class Test {
public static void main(String[] args) {
List<String> strList = new ArrayList<String>();
strList.add("语文:99");
strList.add("数学:98");
strList.add("英语:100");
strList.remove(0);
}
}
在执行这四条语句时,是这么变化的:

其中,add操作将元素放在数组的末尾,remove(0)操作可以理解为删除index为0的节点,并将后面元素移到0处。
第2部分 ArrayList数据结构
ArrayList包含了两个重要的对象:elementData和size。
(1)elementData是Object[]类型的数组,它保存了添加到ArrayList中的元素。
(2)size则是动态数组的实际元素大小。
private static final int DEFAULT_CAPACITY = ;
private static final Object[] EMPTY_ELEMENTDATA = {};
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
transient Object[] elementData; // non-private to simplify nested class access
private int size;
第3部分 ArrayList源码api解析
3.1 add()
当我们在ArrayList中增加元素的时候,会使用add函数。他会将元素放到末尾。具体实现如下:
/**
* Appends the specified element to the end of this list.*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
我们可以看到他的实现其实最核心的内容就是ensureCapacityInternal。这个函数其实就是自动扩容机制的核心。我们依次来看一下他的具体实现
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
// 扩展为原来的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:
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;
}
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;
}
也就是说,当增加数据的时候,如果ArrayList的大小已经不满足需求时,那么就将数组变为原长度的1.5倍,之后的操作就是把老的数组拷到新的数组里面。例如,默认的数组大小是10,也就是说当我们add 10个元素之后,再进行一次add时,就会发生自动扩容,数组长度由10变为了15具体情况如下所示:
总结:
(01)ArrayList实际上是通过一个数组去保存数据的。当我们构造ArrayList时;若使用默认构造函数,则ArrayList的默认容量大小是10。
(02)当ArrayList容量不足以容纳全部元素时,ArrayList会重新设置容量:新的容量=原始容量x3/2。
3.2 set()和get()
ArrayList的set和get函数就比较简单了,先做index检查,然后执行赋值或访问操作:
/**
* Replaces the element at the specified position in this list with
* the specified element.*/
public E set(int index, E element) {
rangeCheck(index); E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
/**
* Returns the element at the specified position in this list.*/
public E get(int index) {
rangeCheck(index); return elementData(index);
}
/**
* Checks if the given index is in range. If not, throws an appropriate
* runtime exception.
*/
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
3.3 remove()
/**
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).*/
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);
// 把最后的置null
elementData[--size] = null; // clear to let GC do its work return oldValue;
}
/**
* 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;
}
第4部分 ArrayList遍历方式
ArrayList支持3种遍历方式
(01)第一种,通过迭代器遍历。即通过Iterator去遍历。
public class Test {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(123);
list.add(456);
list.add(789);
Iterator iter = list.iterator();
while (iter.hasNext()) {
Integer value = (Integer) iter.next();
System.out.println(value);
}
}
}
(02) 第二种,随机访问,通过索引值去遍历。
由于ArrayList实现了RandomAccess接口,它支持通过索引值去随机访问元素。
public class Test {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(123);
list.add(456);
list.add(789);
int size = list.size();
for (int i=0; i<size; i++) {
Integer value = list.get(i);
System.out.println(value);
}
}
}
(03) 第三种,for循环遍历。如下:
public class Test {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(123);
list.add(456);
list.add(789);
for (Integer integer : list) {
Integer value = integer;
System.out.println(value);
}
}
}
第5部分 toArray()异常
当我们调用ArrayList中的toArray(),可能遇到过抛出"java.lang.ClassCastException"异常的情况。下面我们说说这是怎么回事。
ArrayList提供了2个toArray()函数:
Object[] toArray()
<T> T[] toArray(T[] contents)
调用toArray()函数会抛出"java.lang.ClassCastException"异常,但是调用toArray(T[] contents)能正常返回 T[]。
toArray()会抛出异常是因为 toArray() 返回的是Object[]数组,将Object[]转换为其它类型(如如,将Object[]转换为的Integer[])则会抛出"java.lang.ClassCastException"异常,因为Java不支持向下转型。具体的可以参考前面ArrayList.java的源码介绍部分的toArray()。
解决该问题的办法是调用<T> T[] toArray(T[] contents) , 而不是Object[] toArray()。
调用 toArray(T[] contents) 返回T[]的可以通过以下几种方式实现。
// toArray(T[] contents)调用方式一
public static Integer[] vectorToArray1(ArrayList<Integer> v) {
Integer[] newText = new Integer[v.size()];
v.toArray(newText);
return newText;
} // toArray(T[] contents)调用方式二。最常用!
public static Integer[] vectorToArray2(ArrayList<Integer> v) {
Integer[] newText = (Integer[])v.toArray(new Integer[0]);
return newText;
} // toArray(T[] contents)调用方式三
public static Integer[] vectorToArray3(ArrayList<Integer> v) {
Integer[] newText = new Integer[v.size()];
Integer[] newStrings = (Integer[])v.toArray(newText);
return newStrings;
}
参考:
http://www.cnblogs.com/skywang12345/p/3308556.html
Class ArrayList
ArrayList其实就那么一回事儿之源码浅析
关于ArrayList
@ArrayList剖析的更多相关文章
- 基于JDK1.8的ArrayList剖析
前言 本文是基于JDK1.8的ArrayList进行分析的.本文大概从以下几个方面来分析ArrayList这个数据结构 构造方法 add方法 扩容 remove方法 (一)构造方法 /** * Con ...
- Java 中Iterator 、Vector、ArrayList、List 使用深入剖析
标签:Iterator Java List ArrayList Vector 线性表,链表,哈希表是常用的数据结构,在进行Java开发时,JDK已经为我们提供了一系列相应的类来实现基本的数据结构.这些 ...
- Java 集合框架 ArrayList 源码剖析
总体介绍 ArrayList实现了List接口,是顺序容器,即元素存放的数据与放进去的顺序相同,允许放入null元素,底层通过数组实现.除该类未实现同步外,其余跟Vector大致相同.每个ArrayL ...
- ArrayList源码剖析
ArrayList简介 ArrayList是基于数组实现的,是一个动态数组,其容量能自动增长,类似于C语言中的动态申请内存,动态增长内存. ArrayList不是线程安全的,只能用在单线程环境下,多线 ...
- 转:【Java集合源码剖析】ArrayList源码剖析
转载请注明出处:http://blog.csdn.net/ns_code/article/details/35568011 本篇博文参加了CSDN博文大赛,如果您觉得这篇博文不错,希望您能帮我投一 ...
- 【java集合框架源码剖析系列】java源码剖析之ArrayList
注:博主java集合框架源码剖析系列的源码全部基于JDK1.8.0版本. 本博客将从源码角度带领大家学习关于ArrayList的知识. 一ArrayList类的定义: public class Arr ...
- 【Java集合源代码剖析】ArrayList源代码剖析
版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/mmc_maodun/article/details/35568011 转载请注明出处:http:// ...
- Java ArrayList源码剖析
转自: Java ArrayList源码剖析 总体介绍 ArrayList实现了List接口,是顺序容器,即元素存放的数据与放进去的顺序相同,允许放入null元素,底层通过数组实现.除该类未实现同步外 ...
- Java 中 Vector、ArrayList、List 使用深入剖析
线性表,链表,哈希表是常用的数据结构,在进行Java开发时,JDK已经为我们提供了一系列相应的类来实现基本的数据结构.这些类均在java.util包中.本文试图通过简单的描述,向读者阐述各个类的作用以 ...
随机推荐
- 005 Hadoop的三种模式区别
1.本地模式 -默认模式. -不对配置文件进行修改. -使用本地文件系统,而不是分布式文件系统. -Hadoop不会启动NameNode.DataNode.ResourceManager.NodeMa ...
- curl之采集QQ空间留言
目录 主要流程解析 注意事项 扩展 完整代码示例 采集效果一览 主要流程解析 首先,打开浏览器登录QQ空间并访问留言列表 由于QQ空间的链接是https,curl方式请求https链接需要突破http ...
- 牛客网 桂林电子科技大学第三届ACM程序设计竞赛 G.路径-带条件的树的直径变形-边权最大,边数偶数的树上的最长路径-树形dp
链接:https://ac.nowcoder.com/acm/contest/558/G 来源:牛客网 路径 小猫在研究树. 小猫在研究路径. 给定一棵N个点的树,每条边有边权,请你求出最长的一条路径 ...
- FPGA In/Out Delay Timing Constaint
先简单说说这段时间遇到的问题.FPGA采集前端scaler的视频数据.像素时钟(随路时钟),视频数据,行场同步,DE.这些信号进入FPGA后.通过CSC(颜色空间转换).输出后的图像有噪点.通过查看时 ...
- react篇章-React Props
state 和 props 主要的区别在于 props 是不可变的,而 state 可以根据与用户交互来改变.这就是为什么有些容器组件需要定义 state 来更新和修改数据. 而子组件只能通过 pro ...
- Python并发编程系列之常用概念剖析:并行 串行 并发 同步 异步 阻塞 非阻塞 进程 线程 协程
1 引言 并发.并行.串行.同步.异步.阻塞.非阻塞.进程.线程.协程是并发编程中的常见概念,相似却也有却不尽相同,令人头痛,这一篇博文中我们来区分一下这些概念. 2 并发与并行 在解释并发与并行之前 ...
- TPS和QPS是什么,他们的区别是什么
一.TPS:Transactions Per Second(每秒传输的事物处理个数),即服务器每秒处理的事务数.TPS包括一条消息入和一条消息出,加上一次用户数据库访问.(业务TPS = CAPS × ...
- [代码审计]某开源商城前台getshell
0x00 前言 这套系统搞了有点久了,漏洞是发现了,但一直卡在某个地方迟迟没拿下来. 下面就分享一下自己审这套系统的整个过程. 0x01 系统简介 略 0x02 审计入口 看到inc\functi ...
- linux驱动之一语点破天机
<const 关键字> 在嵌入式系开发中,const关键字就是“只读”的意思 <为什么要ARM需要进行C语言环境的初始化> 在汇编情况下,指令的跳转,保护现场需要保存的数据 ...
- 如何正确使用 Django的User Model
阅读目录(Content) django——重写用户模型 1.修改配置文件,覆盖默认的User模型 2.引用User模型 3.指定自定义的用户模型 4.扩展Django默认的User 5.自定义用户与 ...