ArrayList即动态数组,能自动扩容,常用于当作某一对象的容器,ArrayList有较快的访问速度,而插入和删除操作则逊于LinkedList。ArrayList不是线程安全的,多线程下可以使用Vector类或者使用Collections.synchronizedList(list) 返回一个线程安全的ArrayList。
此文章简单探讨ArrayList在Java8中的实现,其实就是翻译一下注释(ps:其实读读自带的注释比看任何文章都好,所以本文不删除原注释)
下面是ArryaLIst
中的构造器实现:
/**
* Default initial capacity.
*默认容量为10
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* Shared empty array instance used for empty instances.
*空的对象数组
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.
*默认的空对象数组,如果创建ArrayList时使用空的构造器,则使用此对象数组
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*该数组用于保存数据
*用transient声明一个实例变量,当对象存储时,它的值不需要维持。即不可序列化
*/
transient Object[] elementData; // non-private to simplify nested class access
/**
* The size of the ArrayList (the number of elements it contains).
*ArrayList 大小(元素个数)
* @serial
*/
private int size;
/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*参数指定初始大小,如果为负数抛出异常
*/
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);
}
}
/**
* Constructs an empty list with an initial capacity of ten.
*看代码是直接赋给默认空数组,可这里写初始容量为10?
*猜测应该是注释没跟上新的实现,ArrayList有一个ensureCapacityInternal方法
*当增加元素时,elementData等于DEFAULTCAPACITY_EMPTY_ELEMENTDATA就会
*把最小容量设为默认容量10
*如果错误麻烦大家指出
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*将一个Collection实现类的对象转换为一个ArrayList,首先将调用toArray()
*方法返回object[],然后用copyOf方法将object[]里的值复制一份给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;
}
}
扩容相关方法,这是ArrayList实现动态数组的核心:
/**
* 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
*注意,这个方法是公开的,如果对ArrayList要装的对象数目有所预期
*利用这个方法对数组进行扩容,可以提高效率
*/
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);
}
}
/**
*这个方法竟然没有注释,不过逻辑很简单
*传进来的最小容量没默认大时,最小容量为10
*然后调用ensureExplicitCapacity判断是否需要扩容
*/
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
/**
*也没有注释,不过逻辑很简单
*所需的最小容量比elementData的长度大
*需要扩容,调用grow方法
*/
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
/**
* The maximum size of array to allocate.
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
*数组大小最大为最大int值-8,这是为了考虑溢出
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
* 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
*>>为右移符号,右移即/2,所以首次扩容大小为原来的1.5倍
*如果扩容后空间还不够,则把所需最小容量设为容量大小
*如果所需容量大于最大值MAX_ARRAY_SIZE,进入hugeCapacity方法
*/
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);
}
/**
*这样设计应该是因为担心溢出,溢出后直接抛出异常
* 没有溢出再设为最大的int值
*不过如此大的数据量真有人用ArrayList存吗。。。。
*/
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
鉴于篇幅,将文章分篇,
ArrayList的方法分析在第二篇,内部类分析在第三篇
本文章来自我的个人博客:
http://jimblog.site/blog/articles/88.html