ArrayList简介

  ArrayList是基于数组实现的,是一个动态数组,其容量能自动增长,类似于C语言中的动态申请内存,动态增长内存。

  ArrayList不是线程安全的,只能用在单线程环境下,多线程环境下可以考虑用Collections.synchronizedList(List l)函数返回一个线程安全的ArrayList类,也可以使用concurrent并发包下的CopyOnWriteArrayList类。

  ArrayList实现了Serializable接口,因此它支持序列化,能够通过序列化传输,实现了RandomAccess接口,支持快速随机访问,实际上就是通过下标序号进行快速访问,实现了Cloneable接口,能被克隆。

ArrayList源码

  ArrayList的源码如下(加入了简单的注释,版本号为1.56):

 /**@(#)ArrayList.java 1.56 06/04/21* Copyright 2006 Sun Microsystems, Inc. All rights reserved.* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.*/package java.util;/*** @author  Josh Bloch* @author  Neal Gafter* @version 1.56, 04/21/06* @see       Collection* @see       List* @see     LinkedList* @see       Vector* @since   1.2*/public class ArrayList<E> extends AbstractList<E>implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{private static final long serialVersionUID = 8683452581122892189L;// ArrayList基于该数组实现,用该数组保存数据private transient Object[] elementData;// 实际大小private int size;// 带容量大小的构造函数public ArrayList(int initialCapacity) {super();if (initialCapacity < 0)throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity);this.elementData = new Object[initialCapacity];}// 默认构造函数public ArrayList() {this(10);}// Collection构造函数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);}// 当前容量值为实际个数public void trimToSize() {modCount++;int oldCapacity = elementData.length;if (size < oldCapacity) {elementData = Arrays.copyOf(elementData, size);}}// 确定ArrayList容量// 若容量不足以容纳当前全部元素,则扩容,新的容量=“(原始容量x3)/2 + 1”public void ensureCapacity(int minCapacity) {modCount++;int oldCapacity = elementData.length;if (minCapacity > oldCapacity) {Object oldData[] = elementData;int newCapacity = (oldCapacity * 3)/2 + 1;if (newCapacity < minCapacity)newCapacity = minCapacity;// minCapacity is usually close to size, so this is a win:elementData = Arrays.copyOf(elementData, newCapacity);}}// 返回实际大小public int size() {return size;}// 清空public boolean isEmpty() {return size == 0;}// 是否包含opublic boolean contains(Object o) {return indexOf(o) >= 0;}// 正向查找,返回o的indexpublic 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;}// 逆向查找,返回o的indexpublic 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;}// 克隆函数public Object clone() {try {ArrayList<E> v = (ArrayList<E>) super.clone();v.elementData = Arrays.copyOf(elementData, size);v.modCount = 0;return v;} catch (CloneNotSupportedException e) {// this shouldn't happen, since we are Cloneablethrow new InternalError();}}// 返回ArrayList的Object数组public Object[] toArray() {return Arrays.copyOf(elementData, size);}// 返回ArrayList组成的数组public <T> T[] toArray(T[] a) {if (a.length < size)// Make a new array of a's runtime type, but my contents:return (T[]) Arrays.copyOf(elementData, size, a.getClass());System.arraycopy(elementData, 0, a, 0, size);if (a.length > size)a[size] = null;return a;}// Positional Access Operations// 得到index位置的元素public E get(int index) {RangeCheck(index);return (E) elementData[index];}// 向index插入elementpublic E set(int index, E element) {RangeCheck(index);E oldValue = (E) elementData[index];elementData[index] = element;return oldValue;}// 添加epublic boolean add(E e) {ensureCapacity(size + 1);  // Increments modCount!!elementData[size++] = e;return true;}// 向index插入elementpublic void add(int index, E element) {if (index > size || index < 0)throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size);ensureCapacity(size+1);  // Increments modCount!!System.arraycopy(elementData, index, elementData, index + 1,size - index);elementData[index] = element;size++;}// 移除index位置的元素public E remove(int index) {RangeCheck(index);modCount++;E oldValue = (E) elementData[index];int numMoved = size - index - 1;if (numMoved > 0)System.arraycopy(elementData, index+1, elementData, index,numMoved);elementData[--size] = null; // Let gc do its workreturn oldValue;}// 移除opublic 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;}// 快速移除index位置的元素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; // Let gc do its work}// 清空public void clear() {modCount++;// Let gc do its workfor (int i = 0; i < size; i++)elementData[i] = null;size = 0;}// 添加Collectionpublic boolean addAll(Collection<? extends E> c) {Object[] a = c.toArray();int numNew = a.length;ensureCapacity(size + numNew);  // Increments modCountSystem.arraycopy(a, 0, elementData, size, numNew);size += numNew;return numNew != 0;}// 在index添加Collectionpublic boolean addAll(int index, Collection<? extends E> c) {if (index > size || index < 0)throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);Object[] a = c.toArray();int numNew = a.length;ensureCapacity(size + numNew);  // Increments modCountint numMoved = size - index;if (numMoved > 0)System.arraycopy(elementData, index, elementData, index + numNew,numMoved);System.arraycopy(a, 0, elementData, index, numNew);size += numNew;return numNew != 0;}// 移除fromIndex到toIndex之间的全部元素protected void removeRange(int fromIndex, int toIndex) {modCount++;int numMoved = size - toIndex;System.arraycopy(elementData, toIndex, elementData, fromIndex,numMoved);// Let gc do its workint newSize = size - (toIndex-fromIndex);while (size != newSize)elementData[--size] = null;}// 移除index位置的元素private void RangeCheck(int index) {if (index >= size)throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size);}// java.io.Serializable的写入函数,将ArrayList的“容量,所有的元素值”都写入到输出流中private void writeObject(java.io.ObjectOutputStream s)throws java.io.IOException{// Write out element count, and any hidden stuffint expectedModCount = modCount;s.defaultWriteObject();// Write out array lengths.writeInt(elementData.length);// Write out all elements in the proper order.for (int i=0; i<size; i++)s.writeObject(elementData[i]);if (modCount != expectedModCount) {throw new ConcurrentModificationException();}}// java.io.Serializable的读取函数:根据写入方式读出,先将ArrayList的“容量”读出,然后将“所有的元素值”读出private void readObject(java.io.ObjectInputStream s)throws java.io.IOException, ClassNotFoundException {// Read in size, and any hidden stuffs.defaultReadObject();// Read in array length and allocate arrayint arrayLength = s.readInt();Object[] a = elementData = new Object[arrayLength];// Read in all elements in the proper order.for (int i=0; i<size; i++)a[i] = s.readObject();}
}

ArrayList详细分析

1.构造函数

ArrayList有三个构造函数,如下(英文注释全部删掉,默认代码折叠,太占地方了):

    private transient Object[] elementData;private int size;public ArrayList(int initialCapacity) {super();if (initialCapacity < 0)throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity);this.elementData = new Object[initialCapacity];}public ArrayList() {this(10);}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);}

  从第一句话可以看到,ArrayList本质上是一个Object类型的数组,前面加入了transient关键字,在序列化的时候忽略,但是在最后自己重写了writeObject和readObject这两个函数,第一个是构造传入固定大小的ArrayList,第二个是默认大小为10,第三个是将传入的Collection转成ArrayList。

  序列化有2种方式:

  A、只是实现了Serializable接口。

    序列化时,调用java.io.ObjectOutputStream的defaultWriteObject方法,将对象序列化。

    注意:此时transient修饰的字段,不会被序列化。

  B、实现了Serializable接口,同时提供了writeObject方法。

    序列化时,会调用该类的writeObject方法。而不是java.io.ObjectOutputStream的defaultWriteObject方法。

    注意:此时transient修饰的字段,是否会被序列化,取决于writeObject

2.自动扩容函数

    public void ensureCapacity(int minCapacity) {modCount++;int oldCapacity = elementData.length;if (minCapacity > oldCapacity) {Object oldData[] = elementData;int newCapacity = (oldCapacity * 3)/2 + 1;if (newCapacity < minCapacity)newCapacity = minCapacity;// minCapacity is usually close to size, so this is a win:elementData = Arrays.copyOf(elementData, newCapacity);}}

  关键在这里int newCapacity = (oldCapacity * 3)/2 + 1;新的数组大小是旧的数组大小的二分之三加一,然后调用Arrays.copyOf(elementData, newCapacity);得到新的elementData对象。说到这里我默默的翻看了一下jdk1.7的源码,发现在jdk1.7当中,扩容效率有了本质上的提高,请看下面的代码:(出自jdk1.7)

    public void ensureCapacity(int minCapacity) {if (minCapacity > 0)ensureCapacityInternal(minCapacity);}private void ensureCapacityInternal(int minCapacity) {modCount++;// overflow-conscious codeif (minCapacity - elementData.length > 0)grow(minCapacity);}private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;private void grow(int minCapacity) {// overflow-conscious codeint oldCapacity = elementData.length;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);}

  1.7相比较1.6,自动扩容增加了两个方法,增加了数组扩容时的判断,最重要的是这句话:int newCapacity = oldCapacity + (oldCapacity >> 1);没有再用*3再/2这种低端的玩法,直接采用了移位运算,我不是太懂十进制数的移位运算,经过几次自己的测试发现如果是偶数,这个移位运算正好是一半,如果是奇数,则是向下取整。

3.存储

  第一判断ensureSize,如果够直接插入,否则按照policy扩展,复制,重建数组。

  第二步插入元素。

  ArrayList提供了set(int index, E element)、add(E e)、add(int index, E element)、addAll(Collection<? extends E> c)、addAll(int index, Collection<? extends E> c)这些添加元素的方法。

  3.1. set(int index, E element),取代,而非插入,返回被取代的元素

    public E set(int index, E element) {RangeCheck(index);E oldValue = (E) elementData[index];elementData[index] = element;return oldValue;}

  3.2.add(E e) 增加元素到末尾,如果size不溢出,自动增长

    public boolean add(E e) {ensureCapacity(size + 1);  // Increments modCount!!elementData[size++] = e;return true;}

  3.3.add(int index, E element) 增加元素到某个位置,该索引之后的元素都后移一位

    public void add(int index, E element) {if (index > size || index < 0)throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size);ensureCapacity(size+1);  // Increments modCount!!System.arraycopy(elementData, index, elementData, index + 1,size - index);elementData[index] = element;size++;}

  3.4.后面两个方法都是把集合转换为数组利用c.toArray,然后利用Arrays.copyOF 方法

    public boolean addAll(Collection<? extends E> c) {Object[] a = c.toArray();int numNew = a.length;ensureCapacity(size + numNew);  // Increments modCountSystem.arraycopy(a, 0, elementData, size, numNew);size += numNew;return numNew != 0;}public boolean addAll(int index, Collection<? extends E> c) {if (index > size || index < 0)throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);Object[] a = c.toArray();int numNew = a.length;ensureCapacity(size + numNew);  // Increments modCountint numMoved = size - index;if (numMoved > 0)System.arraycopy(elementData, index, elementData, index + numNew,numMoved);System.arraycopy(a, 0, elementData, index, numNew);size += numNew;return numNew != 0;}

4.删除

一种是按索引删除,不用查询,索引之后的element顺序左移一位,并将最后一个element设为null,由gc负责回收。

    public E remove(int index) {RangeCheck(index);modCount++;E oldValue = (E) elementData[index];int numMoved = size - index - 1;if (numMoved > 0)System.arraycopy(elementData, index+1, elementData, index,numMoved);elementData[--size] = null; // Let gc do its workreturn oldValue;}

5.Arrays.copyOf

  源码如下:

    public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {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;}

  这里有所优化,如果是Object类型的,直接new Object数组,如果不是则通过Array.newInstance(newType.getComponentType(), newLength)方法产生相应的数组类型。通过System.arraycopy实现数组复制,System是个final类,arraycopy是个native方法。

  该方法被标记了native,调用了系统的C/C++代码,在JDK中是看不到的,但在openJDK中可以看到其源码。该函数实际上最终调用了C语言的memmove()函数,因此它可以保证同一个数组内元素的正确复制和移动,比一般的复制方法的实现效率要高很多,很适合用来批量处理数组。Java强烈推荐在复制大量数组元素时用该方法,以取得更高的效率。

6.Arrays.newInstance()的意义

  Java反射技术除了可以在运行时动态地决定要创建什么类型的对象,访问哪些成员变量,方法,还可以动态地创建各种不同类型,不同维度的数组。

  动态创建数组的步骤如下:
    1.创建Class对象,通过forName(String)方法指定数组元素的类型
    2.调用Array.newInstance(Class, length_of_array)动态创建数组

  访问动态数组元素的方法和通常有所不同,它的格式如下所示,注意该方法返回的是一个Object对象
  Array.get(arrayObject, index)

 

  为动态数组元素赋值的方法也和通常的不同,它的格式如下所示, 注意最后的一个参数必须是Object类型
  Array.set(arrayObject, index, object)

  动态数组Array不单可以创建一维数组,还可以创建多维数组。步骤如下:
    1.定义一个整形数组:例如int[] dims= new int{5, 10, 15};指定一个三维数组
    2.调用Array.newInstance(Class, dims);创建指定维数的数组

  访问多维动态数组的方法和访问一维数组的方式没有什么大的不同,只不过要分多次来获取,每次取出的都是一个Object,直至最后一次,赋值也一样。

  动态数组Array可以转化为普通的数组,例如:
  Array arry = Array.newInstance(Integer.TYPE,5);
  int arrayCast[] = (int[])array;

7.为何要序列化

  ArrayList 实现了java.io.Serializable接口,在需要序列化的情况下,复写writeObjcet和readObject方法提供适合自己的序列化方法。

  1、序列化是干什么的?

    简单说就是为了保存在内存中的各种对象的状态(也就是实例变量,不是方法),并且可以把保存的对象状态再读出来。虽然你可以用你自己的各种各样的方法来保存object states,但是Java给你提供一种应该比你自己好的保存对象状态的机制,那就是序列化。

  2、什么情况下需要序列化

    a)当你想把的内存中的对象状态保存到一个文件中或者数据库中时候;

    b)当你想用套接字在网络上传送对象的时候;

    c)当你想通过RMI传输对象的时候;

8.总结

  8.1.Arraylist基于数组实现,是自增长的

  8.2.非线程安全的

  8.3.插入时可能要扩容,删除时size不会减少,如果需要,可以使用trimToSize方法,在查询时,遍历查询,为null,判断是否是null, 返回; 如果不是null,用equals判断,返回

    /*** Returns <tt>true</tt> if this list contains the specified element.* More formally, returns <tt>true</tt> if and only if this list contains* at least one element <tt>e</tt> such that* <tt>(o==null ? e==null : o.equals(e))</tt>.** @param o element whose presence in this list is to be tested* @return <tt>true</tt> if this list contains the specified element*/public boolean contains(Object o) {return indexOf(o) >= 0;}/*** 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* <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;}

  8.4. 允许重复和 null 元素

————————————————————————————————————————————————————————————

参考资料:

【Java集合源码剖析】ArrayList源码剖析

集合类学习之Arraylist 源码分析

转载于:https://www.cnblogs.com/babycomeon/p/5630482.html

Java集合源码分析(二)ArrayList相关推荐

  1. Java集合源码解析之ArrayList

    uml类图: 基本简介: ArrayList的底层数据结构是数组,所以内存需要为arrayList保证有足够的连续的内存空间. 添加操作会导致数组扩容,数组扩容比较消耗性能. 非尾部的添加和删除元素操 ...

  2. java集合源码分析

    List,Set,Map都是接口,前两个继承Collection接口,Map为独立接口 Set的实现由HashSet,LinkedHashSet,TreeSet List下有ArrayList,Vec ...

  3. java集合源码分析之HashMap

    UML类图: 基本简介: 底层的数据结构是数组,数组的元素类型是链表或者红黑树. 元素的添加可能会触发数组的扩容,会使元素重新哈希放入桶中,效率比较低. 元素在不扩容的情况下添加效率高,查找.删除.修 ...

  4. java地图源码_Java集合源码分析(四)HashMap

    一.HashMap简介 1.1.HashMap概述 HashMap是基于哈希表的Map接口实现的,它存储的是内容是键值对映射.此类不保证映射的顺序,假定哈希函数将元素适当的分布在各桶之间,可为基本操作 ...

  5. Java学习集合源码分析

    集合源码分析 1.集合存在的原因 可以用数组来表示集合,那为什么还需要集合? 1)数组的缺陷 ​ 在创建数组时,必须指定长度,一旦指定便不能改变 数组保存必须是同一个类型的数据 数组的增加和删除不方便 ...

  6. 源码 解析_最详细集合源码解析之ArrayList集合源码解析

    从今天开始我会将集合源码分析陆陆续续整理,写成文章形成集合源码系列文章,方便大家学习 ArrayList集合源码其实相对比较简单,整个源码结构相对于HashMap等源码要好理解的多:先来看下Array ...

  7. SpringBoot源码分析(二)之自动装配demo

    SpringBoot源码分析(二)之自动装配demo 文章目录 SpringBoot源码分析(二)之自动装配demo 前言 一.创建RedissonTemplate的Maven服务 二.创建测试服务 ...

  8. 【Android 事件分发】ItemTouchHelper 源码分析 ( OnItemTouchListener 事件监听器源码分析 二 )

    Android 事件分发 系列文章目录 [Android 事件分发]事件分发源码分析 ( 驱动层通过中断传递事件 | WindowManagerService 向 View 层传递事件 ) [Andr ...

  9. java web开源项目源码_超赞!推荐一个专注于Java后端源码分析的Github项目!

    大家好,最近有小伙伴们建议我把源码分析文章及源码分析项目(带注释版)放到github上,这样小伙伴们就可以把带中文注释的源码项目下载到自己本地电脑,结合源码分析文章自己本地调试,总之对于学习开源项目源 ...

最新文章

  1. pandas索引复合索引dataframe数据、索引其中一个水平(level)的所特定数据行、指定数据行(index a row of a level)、使用元组tuple表达复合索引的指定行
  2. 如何使用JSON和Servlet创建JQuery DataTable
  3. 启动efi_efi启动模式对比bios启动模式有哪些优势【详细介绍】
  4. 杭电1710 (已知二叉树前中序 求后序)
  5. 【转】Qt之文件操作 QFile
  6. 力扣——合并两个有序链表
  7. 最新语言表示方法XLNet
  8. python3随机种子的使用及理解
  9. form表单样式案例
  10. 【C语言作业】一个数如果恰好等于它的因子之和,这个数就称为完整数。例如6的因子为1、2、3,而6=1+2+3,因此6是完数,编程找出1000之内的所有完整数
  11. Android更换皮肤解决方案
  12. 微信小程序选择图片并转base64
  13. [区块链安全-Ethernaut]附加GoodSamaritan解题思路
  14. matlab蜂窝异构网络基站用户矩阵 依照最近距离配对/快速计算两矩阵彼此距离
  15. 后端程序员福音 -- TellMe 推送助手
  16. 拍案叫绝的算法(二)
  17. Ubuntu 下安装 苹果主题界面Mac Sierra Theme
  18. 电解电容的耐压选择:
  19. 阿里巴巴集团告别 CTO?
  20. android nmea 工具,Android模拟GPS数据生成kml和nmea文件

热门文章

  1. 聊聊flink的ConnectionManager
  2. jquery文件的引入
  3. Django 前后台的数据传递
  4. 不用vim-airline/lightline.vim, 如何使用纯手工制作一个漂亮的 vim 状态栏
  5. emmc boot1 boot2 partition
  6. 雅虎开源发布/订阅消息平台Pulsar
  7. 自建邮件服务器给企业带来的商业价值
  8. uva 10453 - Make Palindrome(dp)
  9. 转载:赶集网部门老大回应热帖《我在赶集网的两个月》
  10. Apache2 之虚拟主机设置指南