据说jdk6还是10,jdk8初始容量是0,
jdk8源码如下:
#version jdk1.8
private static final int DEFAULT_CAPACITY = 10;
private static final Object[] EMPTY_ELEMENTDATA = {};
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
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);
}
}
public ArrayList() {
//private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
this.elementData = DEFAULTCAPACITY_EMPTY_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;
}
}
明显初始容量是0,还有一点不明白,为什么initialCapacity 大于0和等于0要分开判断,看了看jdk7发现它是将大于0和等于0一起判断的,它的默认大小也是10
#version jdk1.7
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
public ArrayList() {
this(10);
}
个人觉得将等于0的情况单独列出是为了避免再次new对象,减少资源的开销,同样默认大小设置成0是为了节省不必要时候浪费空间,在添加第一个元素时候开始扩容,这也体现了赖加载的思想
调用add方法扩容jdk1.8
#version jdk1.8
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);
}
}
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
在每个add方法中都会调用ensureCapacityInternal方法,所以保证空间为0时候一次扩容成DEFAULT_CAPACITY=10
当我看到这里我就明白了jdk8为什么要将初始容量为0单独区分开,这样还可以方便使用==来判断elementData和DEFAULT_CAPACITY_EMPTY_ELEMENTDATA是不是一个对象,如果使用new创建容量为0的对象,这个就不能判断,顺便来看看jdk1.7对应位置是怎样写的(说不定能看见bug,我想多了哈哈哈)
#version jdk1.7
private void ensureCapacityInternal(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
果然jdk1.7中采用的是做减法的方案
菜鸟自学心里历程,大神莫笑,有问题望大家批评指正