java1.7集合源码阅读:ArrayList
ArrayList是jdk1.2开始新增的List实现,首先看看类定义:
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
...........
}
ArrayList实现List接口,上层接口是Collection,顶级接口是Iterable,同时还实现了Cloneable、Serializable、RandomAccess接口,以支持克隆、序列化、快速访问。
ArrayList初始容量为10,同时也支持初始化指定初始容量以及使用另一个集合作为初始参数,真正存储数据的是:
private transient Object[] elementData;
......
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
ArrayList内部以数组结构存储数据,相关add、get等方法基本上都是对数组的相关操作,但在增删操作的时候会进行边界检查,增加操作时还要验证容量,当容量不够时会进行扩容.
验证边界:
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
} /**
* A version of rangeCheck used by add and addAll.
*/
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
容量验证及扩容:
/**
* Increases the capacity of this <tt>ArrayList</tt> instance, if
* necessary, to ensure that it can hold at least the number of elements
* specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
public void ensureCapacity(int minCapacity) {
int minExpand = (elementData != EMPTY_ELEMENTDATA)
// any size if real element table
? 0
// larger than default for empty table. It's already supposed to be
// at default size.
: DEFAULT_CAPACITY; if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
} 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);
}
扩容时,为原容量的1.5倍。
ArrayList对Iterator接口的实现:
/**
* 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();
}
} final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
当对ArrayList进行for循环时,如有对集合进行增删改操作时,会报产生ConcurrentModificationException异常。
特别注意:ArrayList不是线程安全的,存在线程安全问题可使用Vector。
java1.7集合源码阅读:ArrayList的更多相关文章
- java1.7集合源码阅读: Vector
Vector是List接口的另一实现,有非常长的历史了,从jdk1.0开始就有Vector了,先于ArrayList出现,与ArrayList的最大区别是:Vector 是线程安全的,简单浏览一下Ve ...
- java1.7集合源码阅读: Stack
Stack类也是List接口的一种实现,也是一个有着非常长历史的实现,从jdk1.0开始就有了这个实现. Stack是一种基于后进先出队列的实现(last-in-first-out (LIFO)),实 ...
- 【JDK1.8】JDK1.8集合源码阅读——ArrayList
一.前言 在前面几篇,我们已经学习了常见了Map,下面开始阅读实现Collection接口的常见的实现类.在有了之前源码的铺垫之后,我们后面的阅读之路将会变得简单很多,因为很多Collection的结 ...
- 关于java1.7集合源码阅读
工作中每天都会和java集合打交道,虽然以前也看过jdk源码的实现,但有些东西时间长了还是会遗忘,或者有些实现在新版本中有了新的变化,俗话说"温故而知新",所以打算再阅读一下相关源 ...
- java1.7集合源码阅读:LinkedList
先看看类定义: public class LinkedList<E> extends AbstractSequentialList<E> implements List< ...
- 集合源码阅读——ArrayList
ArrayList 关键点: >>扩容每次扩容1.5倍 >>modcount的作用 >>ArrayList的父类AbstractList的成员变量 >> ...
- java1.7集合源码阅读:ArrayBlockingQueue
ArrayBlockingQueue是一个先进先出线程安全的队列,队列头部是进入队列时间最长的元素,队尾是进入队列时间最短的元素,同时队列的最大容量是固定的. 先看类定义: public class ...
- 【JDK1.8】JDK1.8集合源码阅读——IdentityHashMap
一.前言 今天我们来看一下本次集合源码阅读里的最后一个Map--IdentityHashMap.这个Map之所以放在最后是因为它用到的情况最少,也相较于其他的map来说比较特殊.就笔者来说,到目前为止 ...
- 【JDK1.8】JDK1.8集合源码阅读——总章
一.前言 今天开始阅读jdk1.8的集合部分,平时在写项目的时候,用到的最多的部分可能就是Java的集合框架,通过阅读集合框架源码,了解其内部的数据结构实现,能够深入理解各个集合的性能特性,并且能够帮 ...
随机推荐
- python读取文件
请参考:http://www.cnblogs.com/sysuoyj/archive/2012/03/14/2395789.html
- JavaScript - 问题集 - 含function的json对象与json字符串之间相互转换
基本的转换为:JSON.parse与JSON.stringify. 但是json数据中含function,则转换后,function会丢失,如: var json={ test:'test', log ...
- java线上编程网站
自带测试 http://codingbat.com/prob/p145416
- python学习笔记四:lambda表达式和switch
一.定义 lambda arg1,arg2... : returnValue 二.示例 #!/usr/bin/python def f(x,y): return x*y print f(2,3) g ...
- leetcode 【 Linked List Swap Nodes in Pairs 】 python 实现
题目: Swap Nodes in Pairs Given a linked list, swap every two adjacent nodes and return its head. For ...
- 自动化测试(二)如何用python写一个用户登陆功能
需求信息: 写一个判断登录的程序: 输入: username password 最大错误次数是3次,输入3次都没有登录成功,提示错误次数达到上限 需要判断输入是否为空,什么也不输入,输入一个空格.n个 ...
- 【志银】Ubuntu Apache2配置SSL证书
1.准备工作 证书文件:zain.crt.zain.key /etc/apache2/文件夹下新建ssl 文件夹,将证书文件放入/etc/apache2/ssl 2.配置SSL证书 打开/etc/ap ...
- HDU 4455 Substrings ( DP好题 )
这个……真心看不出来是个DP,我在树状数组的康庄大道上欢快的奔跑了一下午……看了题解才发现错的有多离谱. 参考:http://www.cnblogs.com/kuangbin/archive/2012 ...
- JavaWeb笔记(六)MVC与三层架构
MVC M Model 模型 JavaBean 完成具体的业务操作,如:查询数据库,封装对象 V View 视图 JSP 展示数据 C Controller 控制器 Servlet 获取用户输入,调用 ...
- 对象内存 (扩展 Data Structure Alignment)
对于一个class object来说,我们需要多少内存才能表现出来,大致分为3类,这里在前面文章有内存图 (1)非静态数据成员的综合大小,这也符合了c++对象模型的结构 (2)填充字节,就是我们所说的 ...