[/code]ArrayList其中有两个构造器,一个ArrayList(),一个ArrayList(int initialCapacity).我想大家一定是经常用第一个。下面看看这两个构造器的区别。
先举个例子:
[code="java"]List<String> arrayList = new ArrayList<String>();
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
arrayList
.add(new String(
"ssssssssssssssssssssssssssssssssssssssssssssssssssss"
+ "sssssssssssssssssssssssssssssssssssssssssssssss"
+ "sssssssssssssssssssssssssssssssssssssssssssssssssss"
+ "sssssssssssssssssssss"));
}
System.out.println((System.currentTimeMillis() - start) + "ms");
System.out
.println(Runtime.getRuntime().maxMemory() / 1024 / 1024 + "M");
System.out.print("已占用内存:");
System.out.println(Runtime.getRuntime().totalMemory() / 1024 / 1024
+ "M");
运行结果:
391ms
63M
已占用内存:32M
那么用ArrayList(int initialCapacity)这个呢?
344ms
63M
已占用内存:43M
很明显第二个构造器的效率要比第一个高。
public ArrayList() {
this(10);
}
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
很明显,ArrayList()就是调用的ArrayList(int initialCapacity),初始化10个对象,作为对象数组。
再看看:
public boolean add(E e) {
ensureCapacity(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
关键就是这个方法:ensureCapacity(size + 1)
/**
* Increases the capacity of this <tt>ArrayList</tt> instance, if
* necessary, to ensure that it can hold at least the number of elements
* specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
public void ensureCapacity(int minCapacity) {
modCount++;
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
Object oldData[] = elementData;
int newCapacity = (oldCapacity * 3)/2 + 1;
if (newCapacity < minCapacity)
newCapacity = minCapacity;
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
}
很明显了,如果不进行初始化长度,再默认10的情况下,大量add时超过10就得增加数组长度了。所以关于ArrayList,在操作之前最好把长度设定,这样对大大提高效率的。