//属性
//默认初始大小
private static final int DEFAULT_CAPACITY = 10;
//空数组用这个
private static final Object[] EMPTY_ELEMENTDATA = {};
//扩展数组时用来和EMPTY_ELEMETDAT
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
//添加第一个元素时将会扩大多DEFAULT_CAPACITY
transient Object[] elementData;
//数组大小
private int size;
构造函数:
public ArrayList(int initialCapacity) {
// 初始容量大于0,数组大小就是这么多
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);
}
}
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
// 与EMPTY_ELEMENTDATA区分开
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
扩容机制:
// 确保容量足够
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);
}
}
如果elementData不是DEFAULTCAPACITY_EMPTY_ELEMENTDATA,就给minExpand赋值0,否则就是10;如果minCapacity > minExpand,进行精确确保容量
private void ensureExplicitCapacity(int minCapacity) {
//修改次数
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
如果最小容量比数组长度大就扩容
// 尝试分配最大的数组大小,防止OutOfMemoryError
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
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;
}
可以看到newCapacity的大小是oldCapacity的1.5倍,如果newCapacity还是小于minCapacity,newCapacity = minCapacity;如果newCapacity已经比最大容量大了,就调用hugeCapacity方法,就直接把整数最大值赋给newCapacity;最后一步调用copyOf复制新数组
标签:int,ArrayList,elementData,newCapacity,private,minCapacity,源码,EMPTY From: https://www.cnblogs.com/xiaoovo/p/16937180.html