由JDK源码学习ArrayList
ArrayList是实现了List接口的动态数组.与java中的数组相比,它的容量能动态增长.ArrayList的三大特点:
① 底层采用数组结构
② 有序
③ 非同步
下面我们从ArrayList的增加元素、获取元素、删除元素三个方面来学习ArrayList。
ArrayList添加元素
因为ArrayList是采用数组实现的,其源代码比较简单.首先我们来看ArrayList的add(E e).以下代码版本是jdk7。
public boolean add(E e) {
// 检查数组容量
ensureCapacityInternal(size + 1);
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
// 计算数组长度
if (elementData == EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
// 模数自增,fail-fast机制
modCount++;
// 如果超过当前数组的长度,调用grow()方法增加数组长度
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
// 新的容量=oldCapacity+oldCapacity/2
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// 创建新的数组,把原数组的数据添加到新数组里面
elementData = Arrays.copyOf(elementData, newCapacity);
}
从上面的代码可以看到,add()方法关键点在于数组容量的处理,添加元素只是将在elementData[size++]处保存e的引用.从grow()方法中我们看到,数组的动态增长时的新长度=原长度+原长度/2.这里和jdk6中有点区别,具体可以查看下jdk6的源码.
ArrayList中还可以添加元素到指定位置.add(index,element):
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1);
// 将index之后的元素往后挪一个位置,腾出elementData[i]的位置
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
代码中看到,add(index,element)方法会造成element[index+1]到element[size]的元素往后挪动,极端情况下(size+1>element.length),要新建数组并且挪动所有元素.这会带来额外的开销,所以,如果不是特别需要,建议使用add(e)方法添加元素.
ArrayList获取元素
ArrayList底层是采用数组存储,所以最简单也最快的获取方式是通过脚标访问.
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
接下来,我们看下ArrayList的遍历.ArrayList有三种遍历方式:脚标访问,foreach循环遍历,迭代器遍历.下面我们来对比下三种方式的效率.
public class ArrayListDemo {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
for(int i = 0;i<10000000;++i){
list.add(i);
}
System.out.println("access by index spend time : "+printListByIndex(list));
System.out.println("access by for spend time : "+printListByFor(list));
System.out.println("access by iterator spend time : "+printListByIterator(list));
}
public static long printListByIndex(List list) {
if(checkList(list)){
throw new IllegalArgumentException("list is null or list.size=0");
}
long startTime = System.currentTimeMillis();
for(int i=0;i<list.size();++i){
list.get(i);
}
long endTime = System.currentTimeMillis();
return endTime - startTime;
}
public static long printListByFor(List list) {
if(checkList(list)){
throw new IllegalArgumentException("list is null or list.size=0");
}
long startTime = System.currentTimeMillis();
for(Object obj : list){
//
}
long endTime = System.currentTimeMillis();
return endTime - startTime;
}
public static long printListByIterator(List list) {
if(checkList(list)){
throw new IllegalArgumentException("list is null or list.size=0");
}
long startTime = System.currentTimeMillis();
Iterator iterator = list.iterator();
while(iterator.hasNext()){
//
iterator.next();
}
long endTime = System.currentTimeMillis();
return endTime - startTime;
}
public static boolean checkList(List list){
return null==list || list.size()<1;
}
}
运行结果如图:

ps:每次运行的结果可能不同,但在我的几次试验中,用脚标访问的方式是最快的,使用foreach循环是相对而言最慢的.
由上面的运行结果,建议遍历ArrayList时使用脚标遍历,这样效率最高.
ArrayList删除元素
public E remove(int index) {
//检查index合法性
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
// 如果移除最后一个元素,则elementData[--size]==null,
// 如果不是最后一个元素,则将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;
}
由上面的代码,可以知道,如果删除的元素不是最后一个元素,会造成元素的移动.这也会带来额外的开销.
由上面的学习和分析,我们可以得出如下结论:ArrayList底层采用的数组结构,对get(index)、set(index,element)操作具备很好的性能,但频繁的增删会影响ArrayList的性能(数组中元素位置移动的开销或者新建数组转移元素带来的开销).所以ArrayList并不适合频繁增删元素的应用场景,另外,在初始化ArrayList时,如果能够预估ArrayList容量来设置初始容量,会减少ArrayList转移元素时的开销,从而提升应用程序的性能.
以上就是本人对ArrayList源码的学习,欢迎大家一起交流讨论!
由JDK源码学习ArrayList的更多相关文章
- 从JDK源码学习Arraylist
从今天开始从源码去学习一些Java的常用数据结构,打好基础:) Arraylist源码阅读: jdk版本:1.8.0 首先看其构造方法: 构造方法一: 第一种支持初始化容量大小,其中声明一个对象数组, ...
- JDK源码学习系列04----ArrayList
JDK源码学习系列04----ArrayList 1. ...
- JDK源码学习--String篇(二) 关于String采用final修饰的思考
JDK源码学习String篇中,有一处错误,String类用final[不能被改变的]修饰,而我却写成静态的,感谢CTO-淼淼的指正. 风一样的码农提出的String为何采用final的设计,阅读JD ...
- JDK源码学习系列05----LinkedList
JDK源码学习系列05----LinkedList 1.LinkedList简介 LinkedList是基于双向链表实 ...
- JDK源码学习系列03----StringBuffer+StringBuilder
JDK源码学习系列03----StringBuffer+StringBuilder 由于前面学习了StringBuffer和StringBuilder的父类A ...
- JDK源码学习系列02----AbstractStringBuilder
JDK源码学习系列02----AbstractStringBuilder 因为看StringBuffer 和 StringBuilder 的源码时发现两者都继承了AbstractStringBuil ...
- JDK源码学习系列01----String
JDK源码学习系列01----String 写在最前面: 这是我JDK源码学习系列的第一篇博文,我知道 ...
- JDK源码学习笔记——LinkedHashMap
HashMap有一个问题,就是迭代HashMap的顺序并不是HashMap放置的顺序,也就是无序. LinkedHashMap保证了元素迭代的顺序.该迭代顺序可以是插入顺序或者是访问顺序.通过维护一个 ...
- JDK1.8源码学习-ArrayList
JDK1.8源码学习-ArrayList 目录 一.ArrayList简介 为了弥补普通数组无法自动扩容的不足,Java提供了集合类,其中ArrayList对数组进行了封装,使其可以自动的扩容或缩小长 ...
随机推荐
- BeanPostProcessor接口
BeanPostProcessor接口及回调方法图 1.InstantiationAwareBeanPostProcessor:实例化Bean后置处理器(继承BeanPostProcessor) po ...
- Apache mod_rewrite
mod_rewrite是Apache的一个非常强大的功能,它可以实现伪静态页面.下面我详细说说它的使用方法!对初学者很有用的哦! 1.检测Apache是否支持mod_rewrite phpinfo() ...
- 使用auth_request模块实现nginx端鉴权控制
使用auth_request模块实现nginx端鉴权控制 nginx-auth-request-module 该模块是nginx一个安装模块,使用配置都比较简单,只要作用是实现权限控制拦截作用.默认高 ...
- 十七、ThreadPoolExecutor线程池
一.简介 executor接口 executor接口在JDK的java.util.concurrent包下,它只有一个抽象方法: void execute(Runnable command); 这意味 ...
- Fill Table Row(it’s an IQ test question)
Here is a table include the 2 rows. And the cells in the first row have been filled with 0~4. Now yo ...
- php之连接mssql(sql server)新手教程
ps:网上搜了很多教程,讲的都很好,就是都有点漏的地方,花了一天时间查缺补漏终于弄好了(;´༎ຶД༎ຶ`),希望我的教程能帮到新手,还有写博客的时候因为不小心按错一个键,导致重写了,博客园这个编辑器真 ...
- python Django 路由之正则表达式
一.路由系统,URL 1. url(r'^index',views.index) #默认的 url(r'^home',views.Home.as_view()) # ...
- Code Signal_练习题_Add Border
Given a rectangular matrix of characters, add a border of asterisks(*) to it. Example For picture = ...
- 牛客Wannafly挑战赛23F 计数(循环卷积+拉格朗日插值/单位根反演)
传送门 直接的想法就是设 \(x^k\) 为边权,矩阵树定理一波后取出 \(x^{nk}\) 的系数即可 也就是求出模 \(x^k\) 意义下的循环卷积的常数项 考虑插值出最后多项式,类比 \(DFT ...
- 【Codeforces】Helvetic Coding Contest 2017 online mirror比赛记
第一次打ACM赛制的团队赛,感觉还行: 好吧主要是切水题: 开场先挑着做五道EASY,他们分给我D题,woc什么玩意,还泊松分布,我连题都读不懂好吗! 果断弃掉了,换了M和J,然后切掉了,看N题: l ...