昨天在面试中被面试官问道阅读过源码没,,想起前段时间看过几眼ArrayList源码就说看过,,结果一问三不知,今天特意补上。
List相对于数组而言最大的好处是在初始化的时候不用设置容量,可以动态扩增容量,但是List在底层是怎么实现的呢?
/**
* 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 Object[] elementData; // non-private to simplify nested class access
通过查看源码可以知道,其实ArrayList中也是使用数组来存储数据,只不过在类中实现了动态扩充数组的操作,对于ArrayList中的元素数组来说,其初始容量主要由创建的构造函数决定:
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.
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* 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.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
可以看出,如果是空构造函数,则是默认容量为10,当传入参数时,如果参数等于0,则是EMPTY_ELEMENTDATA,如果大于0,则创建改大小的数组(从这里也可以看出,ArrayList的最大容量的int类型最大值)。当然除了这两种构造参数之外,还有一个构造参数:
/**
* 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
*/
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,这个就不多说了。下面主要讲下ArrayList中的数组动态扩充,当调用ArrayList的add方法进行添加元素时,会首先判断当前容量是否够用,即ensureCapacityInternal方法:
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
ensureCapacityInternal方法具体内容如下:首先判断当前数组是否是默认数组,如果是,则求当前大小和默认大小的最大值(保证不小于默认数组的大小),然后调用ensureExplicitCapacity方法判断需求大小(miniCapacity)是否大于现有数组大小(elementData.length)(数组越界)。如果是,则调用grow进行动态扩充。从该方法中可以看出,默认扩充50%,但扩充50%之后依旧小于需求大小则将数组容量设置为需求大小。如果新的容量大于数组最大值(Integer.MAX_VALUE - 8),则判断是否溢出,溢出则报错,否则将数组大小设置为(Integer.MAX_VALUE )。
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_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);
}
/**
* 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
*/
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
*/
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);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
介绍的不清楚还希望大家不要介意,有错误的地方还希望大家多多指正,,,,,,,,,