1.实现接口

public class ArrayList<E> extends AbstractList<E>implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{private static final long serialVersionUID = 8683452581122892189L;...
}

2.变量,构造方法

  private static final int DEFAULT_CAPACITY = 10; //初始大小为10private static final Object[] EMPTY_ELEMENTDATA = {};//private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};transient Object[] elementData; // non-private to simplify nested class accessprivate int size;public ArrayList(int initialCapacity) {if (initialCapacity > 0) {  //传入参数大于0,new一个数组返回this.elementData = new Object[initialCapacity];} else if (initialCapacity == 0) {  //传入参数等于0,将EMPTY_ELEMENTDATA赋值给当前elementData数组this.elementData = EMPTY_ELEMENTDATA;} else {throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity);}}//无参构造,将DEFAULTCAPACITY_EMPTY_ELEMENTDATA赋值给elementDatapublic ArrayList() {this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;}//传入集合,调用Arrays.copyOf方法public ArrayList(Collection<? extends E> c) {elementData = c.toArray();if ((size = elementData.length) != 0) {// c.toArray might (incorrectly) not return Object[] (see 6260652)if (elementData.getClass() != Object[].class)elementData = Arrays.copyOf(elementData, size, Object[].class);} else {// replace with empty array.this.elementData = EMPTY_ELEMENTDATA;}}

具体看这

3.trimToSize

    public void trimToSize() {modCount++;if (size < elementData.length) {elementData = (size == 0)? EMPTY_ELEMENTDATA: Arrays.copyOf(elementData, size);}}

返回变量size长度的集合,注意到modCount++ ,参考AbstractList解析

4.ensureCapacity(扩容)

   public void ensureCapacity(int minCapacity) {int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)// any size if not default element table? 0// larger than default for default empty table. It's already// supposed to be at default size.: DEFAULT_CAPACITY;if (minCapacity > minExpand) {ensureExplicitCapacity(minCapacity);}}private static int calculateCapacity(Object[] elementData, int minCapacity) {if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {return Math.max(DEFAULT_CAPACITY, minCapacity);}return minCapacity;}private void ensureCapacityInternal(int minCapacity) {ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));}private void ensureExplicitCapacity(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); //原长度+原长度/2if (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);}private static int hugeCapacity(int minCapacity) {if (minCapacity < 0) // overflowthrow new OutOfMemoryError();return (minCapacity > MAX_ARRAY_SIZE) ?Integer.MAX_VALUE :MAX_ARRAY_SIZE;}

这段代码最重要的我觉得就是int newCapacity = oldCapacity + (oldCapacity >> 1); 有符号右移,也就是长度除以2

5.通用方法

    public int size() {return size;}public boolean isEmpty() {return size == 0;}public boolean contains(Object o) {return indexOf(o) >= 0;}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;}public 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;}/*** Returns a shallow copy of this <tt>ArrayList</tt> instance.  (The* elements themselves are not copied.) 注释中可以看到这是一个浅克隆 直接返回一个新对象,新对象的modCount = 0** @return a clone of this <tt>ArrayList</tt> instance*/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 Cloneablethrow new InternalError(e);}}public Object[] toArray() {return Arrays.copyOf(elementData, size);}@SuppressWarnings("unchecked")public <T> T[] toArray(T[] a) {if (a.length < size)//将size长度的数组复制给a// 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);//将数组全部元素赋值给aif (a.length > size)a[size] = null;//a数组多余的元素赋值为nullreturn a;}@SuppressWarnings("unchecked")E elementData(int index) {return (E) elementData[index];}public E get(int index) {rangeCheck(index);return elementData(index);}public E set(int index, E element) {rangeCheck(index);E oldValue = elementData(index);elementData[index] = element;return oldValue;}public boolean add(E e) {ensureCapacityInternal(size + 1);  // Increments modCount!!//ensureCapacityInternal方法中modCount++elementData[size++] = e;return true;}public void add(int index, E element) {rangeCheckForAdd(index);ensureCapacityInternal(size + 1);  // Increments modCount!!System.arraycopy(elementData, index, elementData, index + 1,size - index);//index + 1及之后的元素向后移elementData[index] = element;//将元素赋值给indexsize++;}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 从index+1开始长度为的numMoved元素赋值给将elementData 从index开始的元素 index+1以及之后的数据前移elementData[--size] = null; // clear to let GC do its workreturn oldValue;}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;}/** 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}public void clear() {modCount++;// clear to let GC do its workfor (int i = 0; i < size; i++)elementData[i] = null;//强引用赋值为null,内存不足gc回收资源size = 0;}public boolean addAll(Collection<? extends E> c) {Object[] a = c.toArray();int numNew = a.length;ensureCapacityInternal(size + numNew);  // Increments modCountSystem.arraycopy(a, 0, elementData, size, numNew);size += numNew;return numNew != 0;}public boolean addAll(int index, Collection<? extends E> c) {rangeCheckForAdd(index);Object[] a = c.toArray();int numNew = a.length;ensureCapacityInternal(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;}protected void removeRange(int fromIndex, int toIndex) {modCount++;int numMoved = size - toIndex;System.arraycopy(elementData, toIndex, elementData, fromIndex,numMoved);// clear to let GC do its workint newSize = size - (toIndex-fromIndex);for (int i = newSize; i < size; i++) {elementData[i] = null;}size = newSize;}....

6.Iterator

    public ListIterator<E> listIterator(int index) {if (index < 0 || index > size)throw new IndexOutOfBoundsException("Index: "+index);return new ListItr(index);}public ListIterator<E> listIterator() {return new ListItr(0);}public Iterator<E> iterator() {return new Itr();}/*** An optimized version of AbstractList.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;Itr() {}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];}public void remove() {if (lastRet < 0)throw new IllegalStateException();checkForComodification();try {ArrayList.this.remove(lastRet);cursor = lastRet;lastRet = -1; //原本指向的元素已经删除,将其赋值为-1expectedModCount = 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();}final void checkForComodification() {if (modCount != expectedModCount)throw new ConcurrentModificationException();}}/*** 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;}@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];}public void set(E e) {if (lastRet < 0)throw new IllegalStateException();checkForComodification();try {ArrayList.this.set(lastRet, e);} catch (IndexOutOfBoundsException ex) {throw new ConcurrentModificationException();}}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();}}}

所谓优化版本,引入了快速失败迭代器,每次增删改都会调用checkForComodification() 方法
具体看这

7.forEach

    @Overridepublic void forEach(Consumer<? super E> action) {Objects.requireNonNull(action);final int expectedModCount = modCount;@SuppressWarnings("unchecked")final E[] elementData = (E[]) this.elementData;final int size = this.size;for (int i=0; modCount == expectedModCount && i < size; i++) {action.accept(elementData[i]);}if (modCount != expectedModCount) {throw new ConcurrentModificationException();}}

调用forEach方法,需要传入重写accept方法的Consumer接口类型的参数,对每个元素进行消费

其他方法略。

参考资料:
https://blog.csdn.net/weixin_43390562/article/details/101236833
https://blog.csdn.net/u010900284/article/details/83544918

JDK源码解析 - java.util.ArrayList相关推荐

  1. JDK源码笔记-java.util.HashMap

    2019独角兽企业重金招聘Python工程师标准>>> HashMap 的存储实现 当程序试图将多个 key-value 放入 HashMap 中时,以如下代码片段为例: Java代 ...

  2. 【JDK源码】java.util.concurrent.atomic包常用类详解

    java.util.concurrent.atomic原子操作类包里面提供了一组原子变量类.其基本的特性就是在多线程环境下,当有多个线程同时执行这些类的实例包含的方法时,具有排他性,即当某个线程进入方 ...

  3. JDK源码(FutureTask)——java.util.concurrent(十)

    测试代码: https://github.com/kevindai007/springboot_houseSearch/tree/master/src/test/java/com/kevindai/j ...

  4. JDK源码解析 迭代器模式在JAVA的很多集合类中被广泛应用,接下来看看JAVA源码中是如何使用迭代器模式的。

    JDK源码解析 迭代器模式在JAVA的很多集合类中被广泛应用,接下来看看JAVA源码中是如何使用迭代器模式的. 看完这段代码是不是很熟悉,与我们上面代码基本类似.单列集合都使用到了迭代器,我们以Arr ...

  5. JDK源码解析 Integer类使用了享元模式

    JDK源码解析 Integer类使用了享元模式. 我们先看下面的例子: public class Demo {public static void main(String[] args) {Integ ...

  6. JDK源码解析 Comparator 中的策略模式

    JDK源码解析 Comparator 中的策略模式.在Arrays类中有一个 sort() 方法,如下: public class Arrays{public static <T> voi ...

  7. JDK源码解析 Runable是一个典型命令模式,Runnable担当命令的角色,Thread充当的是调用者,start方法就是其执行方法

    JDK源码解析 Runnable是一个典型命令模式, Runnable担当命令的角色,Thread充当的是调用者,start方法就是其执行方法 /命令接口(抽象命令角色) public interfa ...

  8. JDK源码解析 InputStream类就使用了模板方法模式

    JDK源码解析 InputStream类就使用了模板方法模式. 在InputStream类中定义了多个 read() 方法,如下: public abstract class InputStream ...

  9. JDK源码解析 —— IO流中的包装类使用到了装饰者模式

    JDK源码解析 IO流中的包装类使用到了装饰者模式. BufferedInputStream, BufferedOutputStream, BufferedReader, BufferedWriter ...

最新文章

  1. VTK:可视化之Arbitrary3DCursor
  2. LAMP-----3、配置apache实现与php的整合
  3. 前端面试题-url、href、src
  4. html和c的区别,tn-s系统与TN-C的区别是什么
  5. 波形捕捉:(8)使用“捕捉缓冲区”
  6. cache性能优化总结
  7. 软件测试文档类型有哪些?
  8. 《编程珠玑》学习记录第八章算法设计技术
  9. 康佳电视android正在升级包,康佳智能电视KKTV刷机包升级包升级固件下载
  10. 小鑫の日常系列故事(一)——判断对错
  11. jquery的插件有哪些
  12. 用计算机弹人间惊鸿客,逆水寒人间惊鸿客奇遇怎么完成 人间惊鸿客攻略
  13. Port-knocking 简单教程
  14. 信息流广告文案与创意设计
  15. 自我激励的有效方法20个(推荐)
  16. EasyExcel实现Excel文件导入导出功能
  17. 英特尔的指令集体系结构_新指令集将上线:Intel 新版指令集手册确认 Alder Lake 架构的存在...
  18. forward完美转发
  19. CentOS下安裝Nvidia docker 2.0:[Errno 256] No more mirrors to try錯誤及解決方式
  20. Python:垃圾分类小游戏

热门文章

  1. 获取SSL证书private key私钥文件的步骤
  2. 未认证公众号如何跳转其他链接
  3. 如何快速开设海外银行账户
  4. 混乱是怎样炼成的——《C解毒》试读
  5. 我的App-帝都地铁
  6. mysql5.7 只读视图_MySQL 5.7: Innodb read view在只读场景的优化
  7. 展望下未来的计算机400字,展望未来作文400字
  8. 【linux】shell脚本 ps 命令学习
  9. 【Redis】Redis缓存
  10. 【Processing】行走的行星 动态海报 processing艺术与科技