AbstractList

1 类图

2 字段

    // 默认容量
private static final int DEFAULT_CAPACITY = 10;
// 共享的空数组
private static final Object[] EMPTY_ELEMENTDATA = {};
// 共享个空数组,和EMPTY_ELEMENTDATA空数组相比是用于了解当添加第一个元素时数组应该扩容多少
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* ArrayList存储元素的buffer, ArrayList的容量就是这个数组buffer的长度
* 任何拥有DEFAULTCAPACITY_EMPTY_ELEMENTDATA空数组的ArrayList在第一次
* 添加元素的时候都会扩容到DEFAULT_CAPACITY = 10
*/
transient Object[] elementData; // non-private to simplify nested class access
// 持有元素的个数
private int size;

3 构造器

    /**
* 无参数的ArrayList的元素数组是DEFAULTCAPACITY_EMPTY_ELEMENTDATA
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
} /**
* 初始容量为0的ArrayList的元素数组是EMPTY_ELEMENTDAT
*/
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);
}
} /**
* 根据collection的迭代器返回的数据顺序构造一个ArrayList
*/
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
this.elementData = EMPTY_ELEMENTDATA;
}
}

4 增

    /**
* 往列表末尾增加元素
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
  1. 先内部确认容量
  2. 数组buffer末尾添加元素
  3. 返回true
    // 最小容量是当前size+1
private void ensureCapacityInternal(int minCapacity) {
// 如果当前的元素数组是DEFAULTCAPACITY_EMPTY_ELEMENTDATA
// 那么最小容量取min(DEFAULT_CAPACITY, size+1)
// 否则直接取size+1
// 可以认为如果指定了容量,那么对容量的预期越低吗?
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
} ensureExplicitCapacity(minCapacity);
} // 确认容量的核心方法,然后扩容
private void ensureExplicitCapacity(int minCapacity) {
// 修改次数++
modCount++; // 如果最小容量大于当前数组buffer的长度,那么需要扩容的
if (minCapacity - elementData.length > 0)
grow(minCapacity);
} /**
* 最大数组长度
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; /**
* 扩容,最起码可以容纳minCapacity个元素
*/
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
// 新容量是老容量1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
// 取minCapacity和newCapacity的更小值
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);
} // 溢出则抛出错误
// 如果大于MAX_ARRAY_SIZE,取Integer最大值,否则取MAX_ARRAY_SIZE
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}

5 删除

    /**
* 删除指定位置的元素,剩余右边元素都需要向左边移动一位
*/
public E remove(int index) {
rangeCheck(index); // 修改次数+1
modCount++;
E oldValue = elementData(index); int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index, numMoved);
elementData[--size] = null; return oldValue;
} /**
* 索引边界检查
*/
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

7 更新

    /**
* 替换指定位置上的元素
*/
public E set(int index, E element) {
rangeCheck(index); E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}

8 查询

    /**
* 返回指定位置元素
*/
public E get(int index) {
rangeCheck(index); return elementData(index);
} /**
* 返回指定元素第一次出现的索引,如果没有返回-1
*/
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;
}

9 遍历

    /**
* 返回一个迭代器
*/
public Iterator<E> iterator() {
return new Itr();
} private class Itr implements Iterator<E> {
int cursor; // 下一个返回的元素的索引
int lastRet = -1; // 上一个返回的元素的索引,如果没有则返回-1
int expectedModCount = modCount; // 期望的修改数目以及实际的修改数目
public boolean hasNext() {
return cursor != size;
} // 如果实际修改次数和期望修改次数不相等则抛出ConcurrentModificationException
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
} @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();
// 往后遍历,游标+1
cursor = i + 1;
// 上一个返回的元素的索引是i
return (E) elementData[lastRet = i];
} public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification(); try {
// 调用ArrayList.remove,modCount++
ArrayList.this.remove(lastRet);
// 下一个游标还是当前元素,比如说上一个索引0,数字2
// 下一个索引1,数字3,当前游标是1
// 删除2后,游标变成0,还会返回3
// 那么上一个返回的元素就没有了,索引置-1
cursor = lastRet;
lastRet = -1;
// 这里把expectedModCount设置为删除后的modCount
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 traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
} } /**
* 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();
}
}
}

AbstractList源码分析的更多相关文章

  1. 集合源码分析[2]-AbstractList 源码分析

    AbstractList 类型:抽象类 接口的继承以及实现关系 继承AbstractCollection 实现List接口 典型方法实现解析 public List<E> subList( ...

  2. 集合源码分析[3]-ArrayList 源码分析

    历史文章: Collection 源码分析 AbstractList 源码分析 介绍 ArrayList是一个数组队列,相当于动态数组,与Java的数组对比,他的容量可以动态改变. 继承关系 Arra ...

  3. 【集合框架】JDK1.8源码分析之ArrayList(六)

    一.前言 分析了Map中主要的类之后,下面我们来分析Collection下面几种常见的类,如ArrayList.LinkedList.HashSet.TreeSet等.下面通过JDK源码来一起分析Ar ...

  4. JDK Collection 源码分析(2)—— List

    JDK List源码分析 List接口定义了有序集合(序列).在Collection的基础上,增加了可以通过下标索引访问,以及线性查找等功能. 整体类结构 1.AbstractList   该类作为L ...

  5. Java集合源码分析(二)ArrayList

    ArrayList简介 ArrayList是基于数组实现的,是一个动态数组,其容量能自动增长,类似于C语言中的动态申请内存,动态增长内存. ArrayList不是线程安全的,只能用在单线程环境下,多线 ...

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

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

  7. Java集合类源码分析

    常用类及源码分析 集合类 原理分析 Collection   List   Vector 扩充容量的方法 ensureCapacityHelper很多方法都加入了synchronized同步语句,来保 ...

  8. Java中ArrayList源码分析

    一.简介 ArrayList是一个数组队列,相当于动态数组.每个ArrayList实例都有自己的容量,该容量至少和所存储数据的个数一样大小,在每次添加数据时,它会使用ensureCapacity()保 ...

  9. Java集合之ArrayList源码分析

    1.简介 List在数据结构中表现为是线性表的方式,其元素以线性方式存储,集合中允许存放重复的对象,List接口主要的实现类有ArrayList和LinkedList.Java中分别提供了这两种结构的 ...

随机推荐

  1. L1-L11 jupter notebook 文件

    L1-L11 jupter notebook 文件下载地址 https://download.csdn.net/download/xiuyu1860/12157961 包括L12 Transforme ...

  2. el-tab-pane label的文字内容怎样设间距

    el-tab-pane label的文字内容怎样设间距 问题描述: 在使用element-ui的el-tab-pane做标签页时,label属性的位置与样式不能通过style样式直接解决 百度后几乎没 ...

  3. 详解 I/O流

    I/O流是用于处理设备之前信息传输的流,在我们今后的学习甚至是工作中,都是十分重要的. 在我们的日常生活中,也是很常见的,譬如:文件内容的合并.设备之键的文件传输,甚至是下载软件时的断点续传,都可以用 ...

  4. 设计模式 - 模板方法模式详解及其在Spring中的应用

    基本介绍 模板方法模式(Template Method Pattern)也叫模板模式,它在一个抽象类中公开定义了执行它的方法的模板,它的字类可以按需重写方法实现,但调用将以抽象类中定义的方式进行. 简 ...

  5. Serlvet容器与Web应用

    对启动顺序的错误认识 之前一直有个观点,应用运行在Servlet容器中,因为从Servlet容器与Web应用的使用方式来看,确实很有这种感觉. 我们每次都是启动Servlet容器,然后再启动我们的应用 ...

  6. java redis面试专题(附答案)

    1.什么是Redis?简述它的优缺点? Redis的全称是:Remote Dictionary.Server,本质上是一个Key-Value类型的内存数据库,很像 memcached,整个数据库统统加 ...

  7. thinkPHP--关于域名指向的问题

    一般项目的域名指向都是可以直接配置的,在默认的情况下.一般都是指向index.php文件.我就直接上图吧,这里是用我的公司项目名称www.xcj.com为域名. 一般的进入项目,调用默认的控制器: h ...

  8. SpringCloud入门(十一):Sleuth 与 Zipkin分布式链路跟踪

    现今业界分布式服务跟踪的理论基础主要来自于 Google 的一篇论文<Dapper, a Large-Scale Distributed Systems Tracing Infrastructu ...

  9. JavaScript HTMlL DOM对象(下)

    DOM:document operation model 文档操作模型 每个标签都是一个对象. 一.查找元素 DOM 回顾 直接查找 var obj = document.getElementById ...

  10. 解析HTML、JS与PHP之间的数据传输

    在电商网站搭建过程中,前端经常会向后端请求数据,有时候通过HTML.JS和PHP文件的处理来实现数据的连通.通常情况下,用户在HTML中做关键字操作,JS对提交的表单进行数据处理,向后端发起ajax请 ...