ArrayList有三种初始化的方法
public ArrayList()
public ArrayList(int initialCapacity)
public ArrayList(Collection<? extends E> c)
第一种无参的构造方法
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
上面注释写着默认的容量为10,上面的DEFAULTCAPACITY_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 = {};
/**
* 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
实际上就是一个空数组,所以无参的构造方法只是指向一个空数组
然后再看带参数的构造方法
/**
* 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);
}
}
传入一个初始的容量,大于0……,=0……,<0……
有必要一提的是EMPTY_ELEMENTDATA是个空数组;
/**
* Shared empty array instance used for empty instances.
*/
private static final Object[] 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
*/
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// defend against c.toArray (incorrectly) not returning Object[]
// (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
这个方法直接把一个集合转化为数组赋值给elementData。
add方法的实现
通常用的add方法是这样的
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return {@code true} (as specified by {@link Collection#add})
*/
public boolean add(E e) {
modCount++;
add(e, elementData, size);
return true;
}
关于modCount++这个操作我另开博文介绍。下面看add(e,elementData,size)这个函数
size是当前的数组中有多少个元素,不包括新增的。
/**
* This helper method split out from add(E) to keep method
* bytecode size under 35 (the -XX:MaxInlineSize default value),
* which helps when add(E) is called in a C1-compiled loop.
*/
private void add(E e, Object[] elementData, int s) {
if (s == elementData.length)
elementData = grow();
elementData[s] = e;
size = s + 1;
}
当发现此时元素数量和这个数组的长度相等,也就说明满了,将执行扩容操作,也就是grow()函数。如果没满,就赋值,然后元素的数量+1。
下面看grow()函数:
private Object[] grow() {
return grow(size + 1);
}
/**
* 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
* @throws OutOfMemoryError if minCapacity is less than zero
*/
private Object[] grow(int minCapacity) {
return elementData = Arrays.copyOf(elementData,
newCapacity(minCapacity));
}
看上面的第二个函数此时的minCapacity=size+1,执行拷贝函数返回结果给elementData,在拷贝函数里面有两个参数,第一个是老数组,第二个是要扩容的长度。新数组的长度是由newCapacity(minCapacity)决定。下面看此函数
/**
* Returns a capacity at least as large as the given minimum capacity.
* Returns the current capacity increased by 50% if that suffices.
* Will not return a capacity greater than MAX_ARRAY_SIZE unless
* the given minimum capacity is greater than MAX_ARRAY_SIZE.
*
* @param minCapacity the desired minimum capacity
* @throws OutOfMemoryError if minCapacity is less than zero
*/
private int newCapacity(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity <= 0) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
return Math.max(DEFAULT_CAPACITY, minCapacity);
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return minCapacity;
}
return (newCapacity - MAX_ARRAY_SIZE <= 0)
? newCapacity
: hugeCapacity(minCapacity);
}
oldCapacity为老数组的长度,newCapacity为老数组的1.5呗(位运算),下面的if条件判断此时扩容后的数组长度是否满足我要的数组长度,如果条件成立(newCapacity <=minCapacity ),也就是说你这个扩容后还不行,还是太小啊,进入判断体,
这里的DEFAULTCAPACITY_EMPTY_ELEMENTDATA,上面有讲过,是个空数组,如果这个elementData是个空数组,则直接返回minCapacity这个长度作为新数组的长度,小于0抛出异常。下面我们再来看最下面的return 语句,如果此时扩容后的长度符合要求,这个 MAX_ARRAY_SIZE是啥呢?
/**
* The maximum size of array to allocate (unless necessary).
* 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;
扩容后的长度比MAX小,符合要求返回newCapacity,如果扩容后的长度都比最大的都大,执行hegeCapacity函数,下面来看
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE)
? Integer.MAX_VALUE
: MAX_ARRAY_SIZE;
}
这里逻辑很简单,就是通过判断确定返回的是Integer.MAX_VALUE还是MAX_ARRAY_SIZE;