ArrayList实现源码分析

2016-04-11 17:52 by 淮左, 207 阅读, 0 评论, 收藏编辑

本文将以以下几个问题来探讨ArrayList的源码实现
1.ArrayList的大小是如何自动增加的
2.什么情况下你会使用ArrayList?什么时候你会选择LinkedList?
3.如何复制某个ArrayList到另一个ArrayList中去?写出你的代码?
4.在索引中ArrayList的增加或者删除某个对象的运行过程?效率很低吗?解释一下为什么?
5.Interator在ArrayList的实现

关于Java集合的小抄 关于ArrayList的描述:
以数组实现。节约空间,但数组有容量限制。超出限制时会增加50%容量,用System.arraycopy()复制到新的数组,因此最好能给出数组大小的预估值。默认第一次插入元素时创建大小为10的数组。
按数组下标访问元素--get(i)/set(i,e) 的性能很高,这是数组的基本优势。
直接在数组末尾加入元素--add(e)的性能也高,但如果按下标插入、删除元素--add(i,e), remove(i), remove(e),则要用System.arraycopy()来移动部分受影响的元素,性能就变差了,这是基本劣势。

1、ArrayList的大小是如何自动增加的

直接上代码吧,每次add的时候都会判断是否需要扩容,以下是扩容的主要方法

    private void ensureCapacityInternal(int minCapacity) {
if (elementData == 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 static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
//左移1位,相当于除以2,就是容量提高50%
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
//最大的阀值MAX_ARRAY_SIZE
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);
}

2、什么情况下你会使用ArrayList?什么时候你会选择LinkedList?

我们知道ArrayList和LinkedList的数据结构是不同的,ArrayList是以连续的数组进行存储的,所以它的get是常数级别的,LinkedList是双向链表存储的。他的查询最坏情况是n。以为ArrayList是数组存储的,所以当你查找某一指定索引的数据时,它每次删除和指定索引添加都要移动数组的位置,其内部的实现方式是数组复杂用到System.arraycope,是比较影响性能的,而双向链表删除和插入只要找到相应的节点位置,关联下指针,所以性能会更好。

    public void add(int index, E element) {
//判断是否超出了索引
rangeCheckForAdd(index);
//判断是否需要扩容
ensureCapacityInternal(size + 1); // Increments modCount!!
//讲elementData复制到elementData,从index开始复制,从index+1开始粘贴,复制的长度是size-index
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}

以及删除方法

    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;
}

3、如何复制某个ArrayList到另一个ArrayList中去?写出你的代码?

下面就是把某个ArrayList复制到另一个ArrayList中去的几种技术:

使用clone()方法,比如ArrayList newArray = oldArray.clone()

使用ArrayList构造方法,比如:ArrayList myObject = new ArrayList(myTempObject)

其他

    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);
}
}
    public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
size = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
}

综上所述,最终的复制方式都是调用Arrays.copyOf,而Arrays.copyOf是调用System.arrayscopy

    public static <T> T[] copyOf(T[] original, int newLength) {
return (T[]) copyOf(original, newLength, original.getClass());
} 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;
}

4、在索引中ArrayList的增加或者删除某个对象的运行过程?效率很低吗?

这个问题同2,因为添加删除某个索引的数据时,需要整体移动数组,所以效率比较低。
5、Interator在ArrayList的实现

因为这个实现的代码比较简单这里就不多解释了,特别说明下forEachRemaining,这个方法是jdk1.8加上的,支持lamdba表达式,主要是遍历游标后面的数据,看while循环i++

    private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
//游标的位置加1
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}

参考
http://calvin1978.blogcn.com/articles/collection.html/
http://www.importnew.com/9928.html/

Java集合关于ArrayList的更多相关文章

  1. 从源码看Java集合之ArrayList

    Java集合之ArrayList - 吃透增删查改 从源码看初始化以及增删查改,学习ArrayList. 先来看下ArrayList定义的几个属性: private static final int ...

  2. Java集合干货——ArrayList源码分析

    ArrayList源码分析 前言 在之前的文章中我们提到过ArrayList,ArrayList可以说是每一个学java的人使用最多最熟练的集合了,但是知其然不知其所以然.关于ArrayList的具体 ...

  3. java集合之ArrayList,TreeSet和HashMap分析

    java集合是一个重点和难点,如果我们刻意记住所有的用法与区别则是不太现实的,之前一直在使用相关的集合类,但是没有仔细研究区别,现在来把平时使用比较频繁的一些集合做一下分析和总结,目的就是以后在需要使 ...

  4. Java集合:ArrayList的实现原理

    Java集合---ArrayList的实现原理   目录: 一. ArrayList概述 二. ArrayList的实现 1) 私有属性 2) 构造方法 3) 元素存储 4) 元素读取 5) 元素删除 ...

  5. 【源码阅读】Java集合之一 - ArrayList源码深度解读

    Java 源码阅读的第一步是Collection框架源码,这也是面试基础中的基础: 针对Collection的源码阅读写一个系列的文章,从ArrayList开始第一篇. ---@pdai JDK版本 ...

  6. Java集合(六)--ArrayList、LinkedList和Vector对比

    在前两篇博客,学习了ArrayList和LinkedList的源码,地址在这: Java集合(五)--LinkedList源码解读 Java集合(四)--基于JDK1.8的ArrayList源码解读 ...

  7. Java 集合源代码——ArrayList

    (1)可以查看大佬们的 详细源码解析 : 连接地址为 : https://blog.csdn.net/zhumingyuan111/article/details/78884746 (2) Array ...

  8. Java集合:ArrayList (JDK1.8 源码解读)

    ArrayList ArrayList几乎是每个java开发者最常用也是最熟悉的集合,看到ArrayList这个名字就知道,它必然是以数组方式实现的集合 关注点 说一下ArrayList的几个特点,也 ...

  9. java集合-数组ArrayList

    1.简介 ArrayList是java集合框架常用的集合类之一,底层是基于数组来实现容量大小动态变化的. 2.类图(JDK 1.8) 下图是ArrayList实现的接口和继承的类关系图: public ...

随机推荐

  1. Android中获取电池电量

    /** * * @author chrp * *显示当前电池电量 */ public class MainActivity extends Activity { private TextView tv ...

  2. .Net 4.0特性 Tuple元组

    Tuple 字面意思:元组.是.net4.0增加的新特性,是干什么的呢?总结一句,个人觉得这个东西 就是用来在有返回很多种类型的值时可以用到.它提供了8种类型的Tuple,直接看最复杂的那种(其实不是 ...

  3. 如何做实时监控?—— 参考 Spring Boot 实现

    随着 微服务 的流行,相比较以前一个大型应用程序搞定所有需求,我们现在更倾向于把大型应用程序切分成多个微服务,服务之间通过 RPC 调用.微服务架构的好处非常多,例如稳定的服务变化较少,不会被非稳定服 ...

  4. Boost Thread学习笔记

    thread自然是boost::thread库的主 角,但thread类的实现总体上是比较简单的,前面已经说过,thread只是一个跨平台的线程封装库,其中按照所使用的编译选项的不同,分别决定使用 W ...

  5. 使用ServletFileUpload实现上传

    1.首先我们应该为上传的文件建一个存放的位置,一般位置分为暂时和真是目录,那我们就须要获取这俩个目录的绝对路径,在servlet中我们能够这样做 ServletContext application ...

  6. 数据和C

    整数就是没有小数部分的数,在C中小数点永远不会出现在整数中.例如2,-24,2456都是整数,整数以二进制存储,例如7的二进制表示为111,在8位的字节中存储它的前5位为0,将后3位置1. 浮点数即加 ...

  7. Nancy.Host的Web应用

    Nancy.Host实现脱离iis的Web应用 本篇将介绍如何使用Nancy.Host实现脱离iis的Web应用,在开源任务管理平台TaskManagerV2.0代码里面已经使用了Nancy.Host ...

  8. 8592 KMP算法

    8592 KMP算法 时间限制:1000MS  内存限制:1000K 题型: 编程题   语言: 无限制 描写叙述 用KMP算法对主串和模式串进行模式匹配. 本题目给出部分代码.请补全内容. #inc ...

  9. oracle 在操作blob该字段是否会产生很多redo

    操作blob该字段是否会产生很多redo,答案是否定的.以下来做一个实验,測试数据库版本号是11.2.0.1.0: --创建一张表做測试之用 create table test_blob (   id ...

  10. js动态添加Div

    利用JavaScript动态添加Div的方式有很多,在这次开发中有用到,就搜集了一下比较常用的. 一.在一个Div前添加Div <html> <body> <div id ...