java集合系列之ArrayList源码分析(基于jdk1.8)

  ArrayList简介

  ArrayList时List接口的一个非常重要的实现子类,它的底层是通过动态数组实现的,因此它具备查询速度快,增删速度慢的特点。另外数组拥有索引,因此可通过索引直接访问集合中的元素,ArrayList集合中允许存放重复的元素。

  下面将对ArrayList集合中的重要方法的底层实现做一下简单的介绍,如有错误,请指正。

  • ArrayList的成员变量:
  1.   //序列化id
  2. private static final long serialVersionUID = 8683452581122892189L;
  3. //默认初始化容量
  4. private static final int DEFAULT_CAPACITY = 10;/**
  5. * 一个空数组,如果使用带参构造方法创建ArrayList对象,并且传入的参数为0,直接将elementData = EMPTY_ELEMENTDATA。
  6. */
  7. private static final Object[] EMPTY_ELEMENTDATA = {};
  8.  
  9. /**
  10. * 另一个空数组,如果使用无参构造方法创建ArrayList对象,直接将elementData = EMPTY_ELEMENTDATA。
  11. */
  12. private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
  13.  
  14. //实际数据存放的数组
  15. transient Object[] elementData; // non-private to simplify nested class access
  16.  
  17. //数组中包含元素的数量
  18. private int size;

  需要注意的是ArrayList从父类那里继承了一个非常重要的成员变量modCount,用来记录数组被修改的次数(增、删、清空数组该变量都会自增),这个变量在并发修改异常时会再次讲解

  1. protected transient int modCount = 0;
  • ArrayList的构造方法:
  1. //带参构造
    public ArrayList(int initialCapacity) {
  2. if (initialCapacity > 0) {//传入的参数大于0,创建数组
  3. this.elementData = new Object[initialCapacity];
  4. } else if (initialCapacity == 0) {//长度为0,赋值为空数组常量,此时add,初始化容量为1
  5. this.elementData = EMPTY_ELEMENTDATA;
  6. } else {//小于0,抛出非法参数异常,并将该参数输出
  7. throw new IllegalArgumentException("Illegal Capacity: "+
  8. initialCapacity);
  9. }
  10. }
  11. /**
  12. * 空参构造,此时add元素时,初始化容量变为10
  13. */
  14. public ArrayList() {
  15. this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
  16. }
  17. /**
  18. * 将一个Collection对象转换成数组,然后将这个数组的引用赋给elementData,前提这个Collection对象中存放的是E或者E的子类
  19. */
  20. public ArrayList(Collection<? extends E> c) {
  21. elementData = c.toArray();
  22. if ((size = elementData.length) != 0) {
  23. // c.toArray might (incorrectly) not return Object[] (see 6260652)这个地方是jdk的一个bug不用考虑
  24. if (elementData.getClass() != Object[].class)
  25. elementData = Arrays.copyOf(elementData, size, Object[].class);
  26. } else {
  27. // 如果elementData为空,则指向空数组EMPTY_ELEMENTDATA
  28. this.elementData = EMPTY_ELEMENTDATA;
  29. }
  30. }
  • ArrayList的添加元素
  1. /**
  2. * 添加元素(添加到数组最后):
  3. * 1.确保数组已使用长度+1之后能存放下一个数据(ensureCapacityInternal())
  4. * 2.在size位置处添加元素,并将size自增(元素个数+1)
  5. * 3.返回true
  6. */
  7. public boolean add(E e) {
  8. ensureCapacityInternal(size + 1); // Increments modCount!!
  9. elementData[size++] = e;
  10. return true;
  11. }
  12.  
  13. /**
  14. * 确保数组的长度能够放得下下一个元素
  15. * 1.如果elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA,即ArrayList对象是通过空参构造创建的,则将最小容量设为10,否则设为还是size+1
  16. * @param minCapacity
  17. */
  18. private void ensureCapacityInternal(int minCapacity) {
  19. if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
  20. minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
  21. }
  22. ensureExplicitCapacity(minCapacity);
  23. }
  24.  
  25. /**
  26. * 修改次数自增1
  27. * 判断数组是否需要扩容,条件为所需的最小容量 > 数组的长度*/
  28. private void ensureExplicitCapacity(int minCapacity) {
  29. modCount++;
  30.  
  31. // overflow-conscious code
  32. if (minCapacity - elementData.length > 0)
  33. grow(minCapacity);
  34. }
  35.  
  36. /**
  37. * 最大数组长度
  38. */
  39. private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
  40.  
  41. /**
  42. * 1. 将原数组的长度扩充为原来的1.5倍,如果此时数组的长度超过了MAX_ARRAY_SIZE,则调用hugeCapacity进行判断
  43. * 2. 数组copy
  44. *
  45. */
  46. private void grow(int minCapacity) {
  47. // overflow-conscious code
  48. int oldCapacity = elementData.length;
  49. int newCapacity = oldCapacity + (oldCapacity >> 1);
  50. if (newCapacity - minCapacity < 0)
  51. newCapacity = minCapacity;
  52. if (newCapacity - MAX_ARRAY_SIZE > 0)
  53. newCapacity = hugeCapacity(minCapacity);
  54. // minCapacity is usually close to size, so this is a win:
  55. elementData = Arrays.copyOf(elementData, newCapacity);
  56. }
  57.  
  58. /**
  59. * 如果minCapacity < 0,抛出OutOfMemoryError
  60. * 否则返回Integer的最大值
  61. */
  62. private static int hugeCapacity(int minCapacity) {
  63. if (minCapacity < 0) // overflow
  64. throw new OutOfMemoryError();
  65. return (minCapacity > MAX_ARRAY_SIZE) ?
  66. Integer.MAX_VALUE :
  67. MAX_ARRAY_SIZE;
  68. }
  1. /**
  2. * 指定索引处添加元素:
  3. * 1. 检查索引必须 0 <= index <=size
  4. * 2. 确保数组已使用长度+1之后能存放下一个数据
  5. * 3. 将该索引及其之后的元素全部后移一位。
  6. * 4. 将新元素添加到该索引处
  7. * 5. 元素数量自增
  8. */
  9. public void add(int index, E element) {
  10. rangeCheckForAdd(index);
  11.  
  12. ensureCapacityInternal(size + 1); // Increments modCount!!
  13. System.arraycopy(elementData, index, elementData, index + 1,
  14. size - index);
  15. elementData[index] = element;
  16. size++;
  17. }
  18.  
  19.   private void rangeCheckForAdd(int index) {
  20. if (index > size || index < 0)
  21. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  22. } 
  1. /**
  2. * 将集合中的元素全部添加到ArrayList对象中:
  3. * 1.将集合转变成数组
  4. * 2.确保当前数组的长度能够放的下size+所添加数组的长度
  5. * 3.数组copy
  6. * 4.size增加
  7. * 5.返回添加是否成功
  8. */
  9. public boolean addAll(Collection<? extends E> c) {
  10. Object[] a = c.toArray();
  11. int numNew = a.length;
  12. ensureCapacityInternal(size + numNew); // Increments modCount
  13. System.arraycopy(a, 0, elementData, size, numNew);
  14. size += numNew;
  15. return numNew != 0;
  16. }
  17.  
  18. /**
  19. *该方法与之前的添加方法类似,将集合放入指定索引处,现将该索引及其之后的元素后移,然后再要添加的数组放到相应位置
  20. */
  21. public boolean addAll(int index, Collection<? extends E> c) {
  22. rangeCheckForAdd(index);
  23.  
  24. Object[] a = c.toArray();
  25. int numNew = a.length;
  26. ensureCapacityInternal(size + numNew); // Increments modCount
  27.  
  28. int numMoved = size - index;
  29. if (numMoved > 0)
  30. System.arraycopy(elementData, index, elementData, index + numNew,
  31. numMoved);
  32.  
  33. System.arraycopy(a, 0, elementData, index, numNew);
  34. size += numNew;
  35. return numNew != 0;
  36. }
  • ArrayList删除元素
  1. /**
  2. * 删除指定索引处的元素,并将该元素返回
  3. * 1. 检查所删除元素的索引是否越界,即保证删除元素的存在,如果不存在抛出IndexOutOfBoundsException
  4. * 2. 修改次数自增
  5. * 3. 如果删除的不是最后一个元素,要将该索引之后的所有元素左移一位
  6. * 4. 将数组最后一个元素设为null,便于垃圾回收,并将数组中的元素数量减1
  7. * 5. 返回所删除的元素(在数组移动之前已经保存在临时变量中)
  8. */
  9. public E remove(int index) {
  10. rangeCheck(index);
  11.  
  12. modCount++;
  13. E oldValue = elementData(index);
  14.  
  15. int numMoved = size - index - 1;
  16. if (numMoved > 0)
  17. System.arraycopy(elementData, index+1, elementData, index,
  18. numMoved);
  19. elementData[--size] = null; // clear to let GC do its work
  20.  
  21. return oldValue;
  22. }
  23.  
  24.   private void rangeCheck(int index) {
  25. if (index >= size)
  26. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  27. }
  28.  
  29. /**
  30. * 删除包含指定数据的元素:
  31. * 1.如果o==null,则使用==比较,否则用equals比较,如果找到返回true
  32. * 2.如果没有找到返回false
  33. */
  34. public boolean remove(Object o) {
  35. if (o == null) {
  36. for (int index = 0; index < size; index++)
  37. if (elementData[index] == null) {
  38. fastRemove(index);
  39. return true;
  40. }
  41. } else {
  42. for (int index = 0; index < size; index++)
  43. if (o.equals(elementData[index])) {
  44. fastRemove(index);
  45. return true;
  46. }
  47. }
  48. return false;
  49. }
  50.  
  51. /**
  52. * 1. 修改次数自增
  53. * 2. 如果删除的不是最后一个元素,要将该索引之后的所有元素左移一位
  54. * 3. 将数组最后一个元素设为null,便于垃圾回收,并将数组元素数量减1
  55. */
  56. private void fastRemove(int index) {
  57. modCount++;
  58. int numMoved = size - index - 1;
  59. if (numMoved > 0)
  60. System.arraycopy(elementData, index+1, elementData, index,
  61. numMoved);
  62. elementData[--size] = null; // clear to let GC do its work
  63. }
  64.  
  65. /**
  66. * 清空集合中的元素:
  67. * 1. 修改次数自增
  68. * 2. 将所有的元素设为null,便于垃圾回收
  69. * 3. size设为0
  70. */
  71. public void clear() {
  72. modCount++;
  73.  
  74. // clear to let GC do its work
  75. for (int i = 0; i < size; i++)
  76. elementData[i] = null;
  77.  
  78. size = 0;
  79. }
  • ArrayList元素迭代的ConcurrentModificationException
  1. /**
  2. * 返回一个迭代器对象new Itr(),该对象为一个内部类
  3. */
  4. public Iterator<E> iterator() {
  5. return new Itr();
  6. }
  7.  
  8. /**
  9. * An optimized version of AbstractList.Itr
  10. */
  11. private class Itr implements Iterator<E> {
  12. int cursor; // index of next element to return
  13. int lastRet = -1; // index of last element returned; -1 if no such
  14. int expectedModCount = modCount;//将集合的修改次数赋值给expectedModCount(期望修改次数)
  15.  
  16. public boolean hasNext() {
  17. return cursor != size;
  18. }
  19.  
  20. /**
  21. * 在迭代遍历集合时,调用该集合的next()方法,首先会检查该集合首先调用checkForComodification()检查是否在迭代过程中发生了修改,
  22. * 如果被修改,则会抛出并发修改异常
  23. */
  24. @SuppressWarnings("unchecked")
  25. public E next() {
  26. checkForComodification();
  27. int i = cursor;
  28. if (i >= size)
  29. throw new NoSuchElementException();
  30. Object[] elementData = ArrayList.this.elementData;
  31. if (i >= elementData.length)
  32. throw new ConcurrentModificationException();
  33. cursor = i + 1;
  34. return (E) elementData[lastRet = i];
  35. }
  36.  
  37. /**
  38. * 用迭代器的remove()方法之所以不会抛出并发修改异常的原因在于,它在删除元素之后,又重新将modCount赋值给expectedModCount,
  39. * 所以在下次调用next()方法进行checkForComodification时,expectedModCount = modCount仍然成立
  40. */
  41. public void remove() {
  42. if (lastRet < 0)
  43. throw new IllegalStateException();
  44. checkForComodification();
  45.  
  46. try {
  47. ArrayList.this.remove(lastRet);
  48. cursor = lastRet;
  49. lastRet = -1;
  50. expectedModCount = modCount;//又重新将modCount赋值给expectedModCount
  51. } catch (IndexOutOfBoundsException ex) {
  52. throw new ConcurrentModificationException();
  53. }
  54. }
  55. /**
  56. * 如果modCount != expectedModCount,则抛出并发修改异常
  57. * 即实际修改的数量不等于并发修改的数量
  58. */
  59. final void checkForComodification() {
  60. if (modCount != expectedModCount)
  61. throw new ConcurrentModificationException();
  62. }
  63. }
  • 其他方法
  1. /**
  2. * 查看集合是否包含对象o,注意参数为Object类型,不是泛型
  3. * 判断元素在数组中第一次出现的索引,并与0比较
  4. */
  5. public boolean contains(Object o) {
  6. return indexOf(o) >= 0;
  7. }
  8.  
  9. /**
  10. * 判断该元素在数组中第一次出现的索引
  11. * 1. 如果o为null,则遍历数组用==比较
  12. * 2. 如果不为null,则遍历数组用equals比较
  13. * 3.如果都没找到,返回-1
  14. */
  15. public int indexOf(Object o) {
  16. if (o == null) {
  17. for (int i = 0; i < size; i++)
  18. if (elementData[i]==null)
  19. return i;
  20. } else {
  21. for (int i = 0; i < size; i++)
  22. if (o.equals(elementData[i]))
  23. return i;
  24. }
  25. return -1;
  26. }
  27.  
  28. /**
  29. * 该元素在数组中最后出现的位置
  30. * 实现方式与indexOf(Object o)方法相同,仅仅需要倒序遍历数组即可
  31. */
  32. public int lastIndexOf(Object o) {
  33. if (o == null) {
  34. for (int i = size-1; i >= 0; i--)
  35. if (elementData[i]==null)
  36. return i;
  37. } else {
  38. for (int i = size-1; i >= 0; i--)
  39. if (o.equals(elementData[i]))
  40. return i;
  41. }
  42. return -1;
  43. }

java集合系列之ArrayList源码分析的更多相关文章

  1. Java集合系列[1]----ArrayList源码分析

    本篇分析ArrayList的源码,在分析之前先跟大家谈一谈数组.数组可能是我们最早接触到的数据结构之一,它是在内存中划分出一块连续的地址空间用来进行元素的存储,由于它直接操作内存,所以数组的性能要比集 ...

  2. java集合系列之LinkedList源码分析

    java集合系列之LinkedList源码分析 LinkedList数据结构简介 LinkedList底层是通过双端双向链表实现的,其基本数据结构如下,每一个节点类为Node对象,每个Node节点包含 ...

  3. Java集合系列[4]----LinkedHashMap源码分析

    这篇文章我们开始分析LinkedHashMap的源码,LinkedHashMap继承了HashMap,也就是说LinkedHashMap是在HashMap的基础上扩展而来的,因此在看LinkedHas ...

  4. Java集合系列:-----------03ArrayList源码分析

    上一章,我们学习了Collection的架构.这一章开始,我们对Collection的具体实现类进行讲解:首先,讲解List,而List中ArrayList又最为常用.因此,本章我们讲解ArrayLi ...

  5. Java集合系列[3]----HashMap源码分析

    前面我们已经分析了ArrayList和LinkedList这两个集合,我们知道ArrayList是基于数组实现的,LinkedList是基于链表实现的.它们各自有自己的优劣势,例如ArrayList在 ...

  6. Java集合系列[2]----LinkedList源码分析

    上篇我们分析了ArrayList的底层实现,知道了ArrayList底层是基于数组实现的,因此具有查找修改快而插入删除慢的特点.本篇介绍的LinkedList是List接口的另一种实现,它的底层是基于 ...

  7. java多线程系列(九)---ArrayBlockingQueue源码分析

    java多线程系列(九)---ArrayBlockingQueue源码分析 目录 认识cpu.核心与线程 java多线程系列(一)之java多线程技能 java多线程系列(二)之对象变量的并发访问 j ...

  8. Java并发系列[2]----AbstractQueuedSynchronizer源码分析之独占模式

    在上一篇<Java并发系列[1]----AbstractQueuedSynchronizer源码分析之概要分析>中我们介绍了AbstractQueuedSynchronizer基本的一些概 ...

  9. Java并发系列[3]----AbstractQueuedSynchronizer源码分析之共享模式

    通过上一篇的分析,我们知道了独占模式获取锁有三种方式,分别是不响应线程中断获取,响应线程中断获取,设置超时时间获取.在共享模式下获取锁的方式也是这三种,而且基本上都是大同小异,我们搞清楚了一种就能很快 ...

随机推荐

  1. jdk concurrent 中 AbstractQueuedSynchronizer uml 图.

    要理解 ReentrantLock 先理解AbstractQueuedSynchronizer 依赖关系. 2

  2. js截屏

    <html><head> <meta name="layout" content="main"> <meta http ...

  3. 更改ubuntu的官方镜像源

    我们自己安装的ubuntu通常默认镜像源是官方的,并不好用,因为网速以及限制比较多,所以为了使用方便,通常都会去更改一下默认的镜像源配置. 这里我们使用清华大学开源镜像软件站,https://mirr ...

  4. nginx 部署ssl证书之后访问用火狐出现SSL_ERROR_RX_RECORD_TOO_LONG此错误,用Google出现ERR_SSL_PROTOCOL_ERROR错误

    server { listen ; server_name xxx.com; ssl_certificate ssl/xxx.pem; ssl_certificate_key ssl/xxx.key; ...

  5. input标签内容改变触发的事件

    原生方法 onchange事件 <input type="text" onchange="onc(this)"> function onc(data ...

  6. LeetCode(72) Edit Distance

    题目 Given two words word1 and word2, find the minimum number of steps required to convert word1 to wo ...

  7. 关于Linux下安装Oracle时报错:out of memory的问题分析说明

    一.说明 在Oracle安装过程中,可能遇到out of memory这种错误,这是由于系统内存不足导致!我们可以通过加内存的方式解决! 而如果是另一种情况呢: 例如我在主机上装了两个Oracle服务 ...

  8. Django之单表的增删改查

      books/urls.py   """books URL Configuration The `urlpatterns` list routes URLs to vi ...

  9. git2--常用命令

    Git 命令详解及常用命令 Git作为常用的版本控制工具,多了解一些命令,将能省去很多时间,下面这张图是比较好的一张,贴出了看一下: 关于git,首先需要了解几个名词,如下: ? 1 2 3 4 Wo ...

  10. Java-从一个字符串获取子字符串

    substring函数 package com.tj; public class MyClass implements Cloneable { public static void main(Stri ...