java.util.ArrayList 源码阅读

一、Summary 概述

Constructor 构造方法

无参构造 ArrayList()

  • ArrayList(Collection<? extends E> c)
    • 这里有个bug, JDK9中得到解决

指定初始容量 ArrayList(int initialCapacity)

二、Method 方法

  • boolean add(E e)
  • void add(int index, E element)
  • boolean addAll(Collection<? extends E> c)
  • boolean addAll(int index, Collection<? extends E> c)
  • remove(int index)
  • remove(Object o) 遍历匹配到对象, 然后fastRemove(int index)
  • boolean removeAll(Collectioin<?> c)
  • boolean retainAll(Collection<?> c)
    • 两个方法公用一个逻辑处理方法 batchRemove(Collection<?> c, boolean complement)
    • 说白了, 就是一个移除/保留交集的问题
  • 查找单个元素的在列表中的位置 int indexOf(Object o)
  • 获取指定位置的元素 get(index) ArrayList 内部存储是一个数组.
  • 设置指定位置的元素 set(inn index, E element)
  • 转化成数组 Object[] toArray()
    • 调用 <T> T[] Arrays.copyOf(T[] original, int newLength)
  • T[] toArray(T[] a)
    • 最终都调用了 System.arrayCopy(), 实际最终都是调用这个方法 (native方法).
  • 克隆 clone() , 对象做了浅拷贝, 但是对其存储容器数组 elementData 做了重新拷贝, 避免了新旧数组之间数据共享问题.
  • 创建子数组 subList(int fromIndex, int toIndex), 返回指定范围内的一个数组视图, 操作都会保留在原数组, 不可以强转为List的实现类,

创建 Iterator 迭代器 public Iterator<E> iterator()

  • An optimized version of AbstractList.Itr
    • 返回一个实现 Iterator 接口的类
  • 以固定的顺序返回对该列表中的元素的迭代器。
  • The returned iterator is fail-fast .返回的迭代器是快速失败的。



创建 ListIterator 迭代器

三、参考文章

posted @ 2022-02-28 20:25  小鸣Cycling  阅读(52)  评论(0编辑  收藏  举报