ArrayList部分源码简析

有参构造

ArrayList

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* 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) {
//如果初始容量大于0
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
//等于0
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}

add方法

add

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
public boolean add(E e) {
//确保内部容量足够
ensureCapacityInternal(size + 1); // Increments modCount!!
//添加元素
elementData[size++] = e;
return true;
}

ensureCapacityInternal

1
2
3
4
private void ensureCapacityInternal(int minCapacity) {
//确保显示容量足够
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}

calculateCapacity

1
2
3
4
5
6
7
8
9
private static int calculateCapacity(Object[] elementData, int minCapacity) {
//如果当前数组还未初始化,即为空数组
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
//返回默认长度10,因为此时minCapacity等于1
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
//如果当前数组已经完成初始化,则直接返回当前size+1
return minCapacity;
}

ensureExplicitCapacity

1
2
3
4
5
6
7
8
private void ensureExplicitCapacity(int minCapacity) {
modCount++;

// overflow-conscious code
//如果当前size+1大于数组长度,则进行扩容
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}

grow方法

grow

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private void grow(int minCapacity) {
// overflow-conscious code
//当前容量
int oldCapacity = elementData.length;
//新容量等于1.5倍当前容量
int newCapacity = oldCapacity + (oldCapacity >> 1);
//如果新容量还不足够长,则新容量直接赋值为minCapacity
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
//如果新容量大于MAX_ARRAY_SIZE(private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;)
if (newCapacity - MAX_ARRAY_SIZE > 0)
//调用hugeCapacity函数
newCapacity = hugeCapacity(minCapacity);

// minCapacity is usually close to size, so this is a win:
//完成新数组的复制
elementData = Arrays.copyOf(elementData, newCapacity);
}

hugeCapacity

1
2
3
4
5
6
7
8
//相当于对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;
}