The capacity is the number of elements the array list can hold before the internal
data structure has to resize.
Use the ensureCapacity() method to check that the internal data structure has enough capacity
before adding elements:
public void ensureCapacity(int minimumCapacity)
import java.util.ArrayList;
/*from w w w . ja v a 2 s. c o m*/
public class MainClass {
public static void main(String[] a) {
ArrayList list = new ArrayList();
list.add("A");
list.ensureCapacity(10);
System.out.println(list.size());
}
}
运行结果如下:
After adding all of the elements, call the trimToSize() method
public void trimToSize()
The trimToSize() method makes sure that there is no unused space in the internal data structure.
import java.util.ArrayList;
//from w ww . j av a2s . c o m
public class MainClass {
public static void main(String[] a) {
ArrayList list = new ArrayList();
list.add("A");
list.ensureCapacity(10);
list.trimToSize();
}
}