1 常量介绍

1.1 ArrayList常量

    /*** 默认初始容量* Default initial capacity.*/private static final int DEFAULT_CAPACITY = 10;/*** 用于空实例的共享空数组实例* Shared empty array instance used for empty instances.*/private static final Object[] EMPTY_ELEMENTDATA = {};/*** 用于默认大小的空实例的共享空数组实例* Shared empty array instance used for default sized empty instances. We* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate(膨胀) when* first element is added.*/private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};/*** 存储ArrayList元素的数组缓冲区,ArrayList的容量是这个数组缓冲区的长度* The array buffer into which the elements of the ArrayList are stored.* The capacity of the ArrayList is the length of this array buffer. Any* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA* will be expanded to DEFAULT_CAPACITY when the first element is added.*/transient Object[] elementData; // non-private to simplify nested class access//非私有以简化嵌套类访问/*** ArrayList的大小(它包含的元素的数量)* The size of the ArrayList (the number of elements it contains).** @serial*/private int size;/*** The maximum size of array to allocate.* Some VMs reserve some header words in an array.* Attempts to allocate larger arrays may result in* OutOfMemoryError: Requested array size exceeds VM limit*/private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

1.2 AbstractList常量

 /*** 改变了size之后,这个值就会变化,如果非法的扰乱了这个值就会抛出异常             * The number of times this list has been <i>structurally modified</i>.* Structural modifications are those that change the size of the* list, or otherwise perturb(扰乱) it in such a fashion(以这种方式) that iterations        * in progress may yield incorrect results.** <p>This field is used by the iterator and list iterator implementation* returned by the {@code iterator} and {@code listIterator} methods.* If the value of this field changes unexpectedly, the iterator (or list* iterator) will throw a {@code ConcurrentModificationException} in* response to the {@code next}, {@code remove}, {@code previous},* {@code set} or {@code add} operations.  This provides* <i>fail-fast</i> behavior, rather than non-deterministic behavior in* the face of concurrent modification during iteration.* 子类可以根据情况判断是否使用,如果使用,只要子类方法有改变size的方法都需要让这个值+1(如果no       * more than one)就会抛出异常* <p><b>Use of this field by subclasses is optional.</b> If a subclass* wishes to provide fail-fast iterators (and list iterators), then it* merely has to increment this field in its {@code add(int, E)} and* {@code remove(int)} methods (and any other methods that it overrides* that result in structural modifications to the list).  A single call to* {@code add(int, E)} or {@code remove(int)} must add no more than* one to this field, or the iterators (and list iterators) will throw* bogus {@code ConcurrentModificationExceptions}.  If an implementation* does not wish to provide fail-fast iterators, this field may be* ignored.*/protected transient int modCount = 0;

2 方法解析

2.1 构造方法

 /*** 默认构造方法,当调用add方法时,会膨胀到默认的大小10* Constructs an empty list with an initial capacity of ten.*/public ArrayList() {this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;}
     /*** 根据传入的初始化值,构造一个指定大小的空数组* Constructs an empty list with the specified initial capacity.** @param  initialCapacity  the initial capacity of the list* @throws IllegalArgumentException if the specified initial capacity*         is negative*/public ArrayList(int initialCapacity) {if (initialCapacity > 0) {this.elementData = new Object[initialCapacity];} else if (initialCapacity == 0) {this.elementData = EMPTY_ELEMENTDATA;} else {throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity);}}
 /*** 构造一个列表,其中包含指定集合的元素,按集合的迭代器返回元素的顺序排列。* Constructs a list containing the elements of the specified* collection, in the order they are returned by the collection's* iterator.** @param c the collection whose elements are to be placed into this list* @throws NullPointerException if the specified collection is null*/public ArrayList(Collection<? extends E> c) {//转换成Object数组elementData = c.toArray();if ((size = elementData.length) != 0) {// c.toArray might (incorrectly) not return Object[] (see 6260652)(JDK9修复)// collection.toArray()理论上应该返回Object[]。然而使用Arrays.asList得到的list,其             // toArray方法返回的数组却不一定是Object[]类型的,而是返回它本来的类型。例如                 // Arrays.asList(String)得到的list,使用toArray会得到String数组。如果向这个数组中存储             // 非String类型的元素,就会抛出ArrayStoreException异常if (elementData.getClass() != Object[].class)//elementData:源数组//size:新的长度//Object[].class:返回的类型elementData = Arrays.copyOf(elementData, size, Object[].class);} else {// replace with empty array.this.elementData = EMPTY_ELEMENTDATA;}}

2.2 常用方法

2.2.1 add(E)
 /*** 将指定的元素添加到此list的末尾* Appends the specified element to the end of this list.** @param e element to be appended to this list* @return <tt>true</tt> (as specified by {@link Collection#add})*/public boolean add(E e) {ensureCapacityInternal(size + 1);  // Increments modCount!!elementData[size++] = e;return true;}

ensureCapacityInternal方法

 private void ensureCapacityInternal(int minCapacity) {//如果是DEFAULTCAPACITY_EMPTY_ELEMENTDATA(也就是调用默认的构造方法),minCapacity=10if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);}ensureExplicitCapacity(minCapacity);}

ensureExplicitCapacity方法

private void ensureExplicitCapacity(int minCapacity) {modCount++;// overflow-conscious code// 如果大于现在的容量,扩容if (minCapacity - elementData.length > 0)grow(minCapacity);}

grow方法

 /*** Increases the capacity to ensure that it can hold at least the* number of elements specified by the minimum capacity argument.** @param minCapacity the desired minimum capacity*/private void grow(int minCapacity) {// overflow-conscious codeint oldCapacity = elementData.length;//oldCapacity >> 1等价于oldCapacity/2(数学上的除)//新的容量为旧容量的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:// newCapacity:源数组// size:新的长度// 拷贝elementData = Arrays.copyOf(elementData, newCapacity);}

hugeCapacity

private static int hugeCapacity(int minCapacity) {if (minCapacity < 0) // overflowthrow new OutOfMemoryError();return (minCapacity > MAX_ARRAY_SIZE) ?Integer.MAX_VALUE :MAX_ARRAY_SIZE;}
2.2.2 add(int,E)
 /*** 从指定的位置插入相应的元素,将当前位于该位置的元素(如果有)和所有后续元素      * 向右移动(将一个元素添加到它们的索引中)* Inserts the specified element at the specified position in this* list. Shifts the element currently at that position (if any) and* any subsequent(后续) elements to the right (adds one to their indices).** @param index index at which the specified element is to be inserted* @param element element to be inserted* @throws IndexOutOfBoundsException {@inheritDoc}*/public void add(int index, E element) {//范围检测rangeCheckForAdd(index);ensureCapacityInternal(size + 1);  // Increments modCount!!//elementData:源数组//index:开始下标//elementData:目标数组//index + 1:目的数组开始下标//size - index:复制长度System.arraycopy(elementData, index, elementData, index + 1,size - index);//指定位置赋值elementData[index] = element;size++;}
2.2.5 get(int)
 /*** 根据下标获取,花费常数时间* Returns the element at the specified position in this list.** @param  index index of the element to return* @return the element at the specified position in this list* @throws IndexOutOfBoundsException {@inheritDoc}*/public E get(int index) {rangeCheck(index);return elementData(index);}
2.2.6 set(int,E)
 /*** 将列表中指定位置的元素替换为指定元素,花费常数时间* Replaces the element at the specified position in this list with* the specified element.** @param index index of the element to replace* @param element element to be stored at the specified position* @return the element previously at the specified position* @throws IndexOutOfBoundsException {@inheritDoc}*/public E set(int index, E element) {rangeCheck(index);E oldValue = elementData(index);elementData[index] = element;return oldValue;}
2.2.7 remove(int)
 /*** 如果存在,从该列表中删除指定元素的第一个匹配项。如果列表不包含该元素,则不更改。* Removes the first occurrence of the specified element from this list,* if it is present.  If the list does not contain the element, it is* unchanged.  More formally, removes the element with the lowest index* <tt>i</tt> such that* <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>* (if such an element exists).  Returns <tt>true</tt> if this list* contained the specified element (or equivalently, if this list* changed as a result of the call).** @param o element to be removed from this list, if present* @return <tt>true</tt> if this list contained the specified element*/public 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;}

fastRemove

 /** Private remove method that skips bounds checking and does not* return the value removed.*/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; // clear to let GC do its work}
2.2.8 remove(Object)
    public 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;}
2.2.9 contains
 /*** 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&nbsp;?&nbsp;e==null&nbsp;:&nbsp;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;}

indexOf

     /*** 返回第一次出现的选定元素的下标,如果没有,返回-1* 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&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,* or -1 if there is no such index.*/public int indexOf(Object o) {//循环遍历(lastIndexOf是从最后开始遍历)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;}
2.2.10 Iterator
 /*** Returns an iterator over the elements in this list in proper sequence.** <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.** @return an iterator over the elements in this list in proper sequence*/public Iterator<E> iterator() {return new Itr();}

Itr

 private class Itr implements Iterator<E> {int cursor;       // index of next element to returnint lastRet = -1; // index of last element returned; -1 if no suchint 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();cursor = i + 1;return (E) elementData[lastRet = i];}//Iterator内部的remove方法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 trafficcursor = i;lastRet = i - 1;checkForComodification();}//保证使用Iterator时没有非法更改内部的元素,否则抛出ConcurrentModificationExceptionfinal void checkForComodification() {if (modCount != expectedModCount)throw new ConcurrentModificationException();}}
2.2.11 ListIterator
 /*** Returns a list iterator over the elements in this list (in proper* sequence).** <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.** @see #listIterator(int)*/public ListIterator<E> listIterator() {return new ListItr(0);}

ListItr

/*** An optimized version of AbstractList.ListItr*/private class ListItr extends Itr implements ListIterator<E> {ListItr(int index) {super();cursor = index;}//判断前面有没有元素public boolean hasPrevious() {return cursor != 0;}public int nextIndex() {return cursor;}public int previousIndex() {return cursor - 1;}//返回当前cursor的上一个元素@SuppressWarnings("unchecked")public E previous() {checkForComodification();int i = cursor - 1;if (i < 0)throw new NoSuchElementException();Object[] elementData = ArrayList.this.elementData;if (i >= elementData.length)throw new ConcurrentModificationException();cursor = i;return (E) elementData[lastRet = i];}//替换由{@link #next} or {@link #previous}返回的最后一个元素//这个调用只能在{@link #remove}和{@link #add}都没有被调用的情况下//并且在最后一次调用{@code next}或之后被调用{@code previous}。public void set(E e) {if (lastRet < 0)throw new IllegalStateException();checkForComodification();try {ArrayList.this.set(lastRet, e);} catch (IndexOutOfBoundsException ex) {throw new ConcurrentModificationException();}}//将指定的元素插入列表。元素被插入到将由{@link #next}返回元素的前面public void add(E e) {checkForComodification();try {int i = cursor;ArrayList.this.add(i, e);cursor = i + 1;lastRet = -1;expectedModCount = modCount;} catch (IndexOutOfBoundsException ex) {throw new ConcurrentModificationException();}}}

ArrayList源码解析——基于JDK1.8相关推荐

  1. ConcurrentHashMap源码解析——基于JDK1.8

    ConcurrentHashMap源码解析--基于JDK1.8 前言 这篇博客不知道写了多久,总之就是很久,头都炸了.最开始阅读源码时确实是一脸茫然,找不到下手的地方,真是太难了.下面的都是我自己阅读 ...

  2. LinkedHashMap源码解析——基于JDK1.8

    前言 LinkedHashMap继承自HashMap.和HashMap不同的是,它维护一条双向链表,解决了遍历顺序和插入顺序一致的问题.并且还对访问顺序提供了相应的支持.因为LinkedHashMap ...

  3. HashMap源码解析——基于JDK1.8

    前言 HashMap数据结构由数组和链表(超过一定数量转换为红黑树)组成,在进行增删查等操作时,首先要定位到元素的所在表的位置,之后再从链表中定位该元素.具体找到表下标的方法是(n - 1) & ...

  4. HashSet源码解析——基于JDK1.8

    前言 HashSet 是一个不允许存储重复元素的集合,它的实现比较简单,只要理解了 HashMap,HashSet 就水到渠成了.当然了解HashMap可以参考我的这篇文章 1 常量介绍 //使用Ha ...

  5. 增加数组下标_数组以及ArrayList源码解析

    点击上方"码之初"关注,···选择"设为星标" 与精品技术文章不期而遇 前言 前一篇我们对数据结构有了个整体的概念上的了解,没看过的小伙伴们可以看我的上篇文章: ...

  6. ArrayList源码解析与相关知识点

    ArrayList源码解析于相关知识点(超级详细) 文章目录 ArrayList源码解析于相关知识点(超级详细) ArrayList的继承关系 Serializable标记接口 Cloneable标记 ...

  7. Spring源码深度解析(郝佳)-学习-源码解析-基于注解注入(二)

    在Spring源码深度解析(郝佳)-学习-源码解析-基于注解bean解析(一)博客中,己经对有注解的类进行了解析,得到了BeanDefinition,但是我们看到属性并没有封装到BeanDefinit ...

  8. 面试官系统精讲Java源码及大厂真题 - 05 ArrayList 源码解析和设计思路

    05 ArrayList 源码解析和设计思路 耐心和恒心总会得到报酬的. --爱因斯坦 引导语 ArrayList 我们几乎每天都会使用到,但真正面试的时候,发现还是有不少人对源码细节说不清楚,给面试 ...

  9. 顺序线性表 ---- ArrayList 源码解析及实现原理分析

    原创播客,如需转载请注明出处.原文地址:http://www.cnblogs.com/crawl/p/7738888.html ------------------------------------ ...

最新文章

  1. 蚂蚁金服“刷脸”支付技术解读:错误率低于百万分之一
  2. STM32时钟配置方法详解
  3. 操作系统---Systemd
  4. 打开pix4d无有效许可_我市两家企业通过危险废物综合经营许可证专家核查
  5. 《研磨设计模式》chap20 享元模式 Flyweight (3)重写应用场景
  6. 波场php转,波场TRC20 Token PHP交互
  7. SQL2005利用ROW_NUMER实现分页的两种常用方式
  8. C#中的集合学习笔记
  9. ffmpeg 时间戳
  10. 【转】SQL Server服务器名称与默认实例名不一致的修复方法
  11. linux mono apache2,如何利用Mono创建Apache+mono环境(2)
  12. nhibernate事务锁表的问题
  13. IDEA+Maven+Git
  14. 还在被网络上各种关于单片机行业的收入搞的眼花缭乱而烦恼吗
  15. 基于 word2vec 模型的文本分类任务
  16. 万字长文 | 关于Filecoin期货与矿机,你想知道的一切都在这
  17. 《神经网络与深度学习》习题答案
  18. Android 实现短信接收监听--(短信动态权限添加)
  19. mrtg流量图不更新了是怎么回事,谁有mrtg的安装及配置文档啊,求!!!
  20. 田蕴章书法讲座《每日一题,每日一字》(2) 文字整理 ——火字、必字与书法笔顺

热门文章

  1. 关于熊猫认证软件IOS安装步骤教程(适用于其他软件)
  2. Tenorshare UltData for Mac(iOS数据恢复备份软件)
  3. page source 保存html,如何让phantomJS webdriver等到加载特定的HTML元素然后返回page.source?...
  4. 如何给网易云笔记添加好用的目录功能,提高生产效率
  5. Java 包装类型和基本数据类型的区别及分别什么时候应用
  6. 【转】分布式锁的实现
  7. 计算机知识的黑板报图片大全,安全知识宣传黑板报图片大全
  8. 黑苹果安装后不能调节分辨率
  9. 2021015979李庚奇实验二
  10. 台式电脑怎么调分辨率_怎么调电脑的分辨率