ArrayList 源码解读     基于JDk 1.7.0_80

public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable

ArrayList的底层是使用数组实现的,因为数组的容量是固定的,要实现可变容量List,所以一定存在着容量检测,数组复制等方法。

对象属性

    /**
* 默认大小
*/
private static final int DEFAULT_CAPACITY = 10; /**
* 空对象数组 ,用来做比较
*/
private static final Object[] EMPTY_ELEMENTDATA = {}; /**
* 存储数据的数组
*/
private transient Object[] elementData; /**
* 大小
*/
private int size;

构造方法

  /**
* 指定大小*/
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
} /**
* 默认
*/
public ArrayList() {
super();
this.elementData = EMPTY_ELEMENTDATA;
} /**
* 传入一个Collection*/
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
size = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
}

add 方法

  public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments 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);
elementData[index] = element;
size++;
}
//判断是否是空数组
private void ensureCapacityInternal(int minCapacity) {
if (elementData == EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
//判断是否达到了数组的容量
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
//增加容量
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
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:
elementData = Arrays.copyOf(elementData, newCapacity);
}

remove 方法

    /**
* Removes the element at the specified position in this list.
*/
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);
//最后一位设为null
elementData[--size] = null; // clear to let GC do its work
return oldValue;
} /**
* Removes the first occurrence of the specified element from this list,
*/
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 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
} private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

get方法

    public E get(int index) {
rangeCheck(index); return elementData(index);
}

set方法

    public E set(int index, E element) {
rangeCheck(index); E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}

内部类Itr 实现了Iterator接口  ,实现了 next()   hasNext()  remove() 三个方法

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 return
// 上次返回的位置
int lastRet = -1; // index of last element returned; -1 if no such
int 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];
} 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();
}
}
   //当你在使用迭代器时,不能使用 使用 set add 等方法,改变 存储的数据
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}

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();
}
}
}

ArrayList 源码解读的更多相关文章

  1. JDK12下的ArrayList源码解读 与 Vector的对比

    ArrayList源码阅读. //测试代码实现如下 private static void arrayList() { ArrayList<String> list = new Array ...

  2. ArrayList源码解读(jdk1.8)

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

  3. 深入理解JAVA集合系列四:ArrayList源码解读

    在开始本章内容之前,这里先简单介绍下List的相关内容. List的简单介绍 有序的collection,用户可以对列表中每个元素的插入位置进行精确的控制.用户可以根据元素的整数索引(在列表中的位置) ...

  4. Java集合ArrayList源码解读

    最近在回顾数据结构,想到JDK这样好的代码资源不利用有点可惜,这是第一篇,花了心思.篇幅有点长,希望想看的朋友认真看下去,提出宝贵的意见.  :) 内部原理 ArrayList 的3个字段 priva ...

  5. java集合之ArrayList源码解读

    源自:jdk1.8.0_121 ArrayList继承自AbstractList,实现了List.RandomAccess.Cloneable.Serializable. ArrayList内部是通过 ...

  6. ArrayList源码解读笔记

    简介: ArrayList是我们开发中非常常用的数据存储容器之一,其底层是数组实现的,我们可以在集合中存储任意类型的数据,ArrayList是线程不安全的,非常适合用于对元素进行查找,效率非常高. 线 ...

  7. Java集合(四)--基于JDK1.8的ArrayList源码解读

    public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess ...

  8. ArrayList源码解读

    在端午节这个节日里,有一个特殊的任务,我带着你一起揭开"ArrayList"的真面目.从成员变量.构造函数.主要方法三部分,对ArrayList有进一步的认识,希望能够帮助你. 一 ...

  9. jdk1.8.0_45源码解读——ArrayList的实现

    jdk1.8.0_45源码解读——ArrayList的实现 一.ArrayList概述 ArrayList是List接口的可变数组的实现.实现了所有可选列表操作,并允许包括 null 在内的所有元素. ...

随机推荐

  1. auditd重启失败

    发现auditd 服务有问题 进行重启 systemctl restart auditd Failed to restart auditd.service: Operation refused, un ...

  2. Nodejs中request出现ESOCKETTIMEDOUT解决方案

    做需求的时候,使用Nodejs的request批量请求某一个接口,由于接口超时,出现 ESOCKETTIMEDOUT,程序中断 为了让程序遇到 ESOCKETTIMEDOUT 之后能够继续执行下去,需 ...

  3. C# asp.net XML格式的字符串显示不全

    前台显示XML字符串显示不全 后台XML字符串使用<xmp></xmp>将XML格式字符串括起来

  4. nginx入门(一)

    什么是nginx? nginx是一款高性能的http 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器.由俄罗斯的程序设计师Igor Sysoev所开发,官方测试nginx能够支支撑5 ...

  5. typescript总结

    1,基础类型 {   布尔值,let isDone:Boolean=true;   数字,let decLiteral:number=true;   字符串,let name:string=" ...

  6. 通过css样式给表格tbody加垂直滚动条

    tbody加滚动条实现思路: 1,把tbody设置成display:block,然后就对其高度设置一个固定值,overflow设置成auto. 2,把thead的tr设置成display:block. ...

  7. openstack stein部署手册 9. neutron

    # 安装程序包 yum -y install openstack-neutron-linuxbridge ebtables ipset # 变更配置文件 mv /etc/neutron/neutron ...

  8. 如何启用Nginx的status功能,查看服务器状态信息?

    如何查看服务器状态信息? 我们可以通过安装Nginx的功能模块,并修改Nginx的主配置文件来实现. 1.编译安装时使用--with-http_stub_status_module开启状态页面模块 [ ...

  9. cut 从文本中提取一段文字并输出

    1.命令功能 cut 从每个文件中截取选定部分并输出. 2.语法格式 cut  option  file 参数说明 参数 参数说明 -b (–bytes) 字节 -c (--characters) 字 ...

  10. [python 学习] IO操作之读写文件

    一.读取全部文件: # -*- coding: utf-8 -*- f = open('qq_url.txt','r'); print f.read(); f.close(); 二.读取规定长度文件 ...