Fork me on Github
Fork me on Github

Joe Dog Software

Proudly serving the Internets since 1999

up arrow ArrayList.ensureCapacity

Have you ever wanted to initialize a java ArrayList to a certain size? You peruse the javadoc and you see what appear to be two different options, one is a constructor option and the other is a chained method.

Here’s the constructor:

ArrayList (int initialCapacity)

Constructs an empty list with the specified initial capacity.

And here’s the method:

void ensureCapacity(int minCapacity)

Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.

And here’s the thing: Neither one changes the logical size of the array. They each change its capacity. That is they change the size it can reach before it has to start copying its values to resize itself. If you do something like the following, you’ll get an IndexOutOfBounds Exception:

ArrayList<String> list = new ArrayList<String>();
list.add(190, "JoeDog");

Exception in thread "main" java.lang.IndexOutOfBoundsException

If you want to initialize an ArrayList to a particular size, you’ll have to roll your own method:

 private static void ensureSize(ArrayList<?> list, int size) {
   while (list.size() < size) {

You can call it like this:

ArrayList<Thing> list = new ArrayList<Thing>();
ensureSize(list, 64);