java ArrayList源码学习,分析
ArrayList 简介
ArrayList是一个动态数组,它能够自动进行扩容。
继承自AbstractList,implements 实现了 List, RandomAccess (随机访问–空接口), Cloneable(克隆–空接口), java.io.Serializable(序列化)
与vector相比,不是线程安全的容器,但效率相对高些,所以在单线程中推荐使用ArrayList,多线程中可以使用Vector
ArrayList :以下均是基于JDK1.8
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
private static final long serialVersionUID = 8683452581122892189L; //序列化UUID
private static final int DEFAULT_CAPACITY = 10; //初始化默认容量
private static final Object[] EMPTY_ELEMENTDATA = {}; //静态 final 空数组,设置容器大小为0时,直接等于这个值
transient Object[] elementData; // 存储数据的Object数组
private int size; //记录实际存储数据的个数
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; //array最大个数
构造器
参数为设置初始化容器的构造函数
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) { //如果容量为0,设置 直接设置为EMPTY_ELEMENTDATA
this.elementData = EMPTY_ELEMENTDATA;
} else { //否则抛出异常
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
默认构造器:
容器容量默认为10
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
集合形式构造器
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;
}
}
内置方法
trimTosize():应该是去除多余的空间,如果存储的个数少于数组的长度,说明有多余的剩余空间,调用Arrays.copyOf()方法
/**
* Trims the capacity of this <tt>ArrayList</tt> instance to be the
* list's current size. An application can use this operation to minimize
* the storage of an <tt>ArrayList</tt> instance.
*/
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
ArrayList扩容机制
确定ArrayList的容量 : 如果当前容量不足以容纳当前的元素的个数,调用ensureExplicitCapacity()方法
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);
}
}
如果容量不足,需要调用grow()
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
调用grow(),真正进行扩容的地方,扩容为1.5倍
/**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length; //oldCapacity为当前容器的长度
int newCapacity = oldCapacity + (oldCapacity >> 1); //新长度为原来长度右移一位,也就是/2,一半,在加上原来的长度
if (newCapacity - minCapacity < 0) //新长度比原来小
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)//新长度比最大size大(也就是Integer的最大值-8)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
// 拷贝原数组中的元素至新数组,并返回新数组的引用
elementData = Arrays.copyOf(elementData, newCapacity); //正常情况下,1.5倍
}
ArrayList常用方法、
ArrayList的内部类–迭代器
迭代器原理:
迭代器是对集合进行遍历, 而每一个集合内部的存储结构都是不同的,所以每一个集合存和取都是不一样, 那么就需要在每一个类中定义hasNext()和next()方法,这样做是可以的,但是会让整个集合体系过于臃肿, 迭代器是将这样的方法向上抽取出接口,然后在每个类的内部,定义自己迭代方式,
好处
- 第一规定了整个集合体系的遍历方式都是hasNext()和next()方法,
- 第二,代码有底层内部实现,使用者不用管怎么实现的,会用即可
private class ListItr extends Itr implements ListIterator
{ 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. 迭代器
2. 随机访问,通过索引
3. for循环遍历
ArrayList的遍历代码就不写了,也都很简单…偷个懒…
还没有评论,来说两句吧...