Course contentsShow
← Java
Lesson 1018 of 2,87024. List ImplementationsFree lesson

Pre-Sizing with ensureCapacity and the Initial Capacity Constructor

How to avoid resizes entirely by specifying capacity upfront when size is known.

Pre-Sizing with ensureCapacity and the Initial Capacity Constructor

You'll learn how to eliminate resize overhead entirely by specifying ArrayList capacity upfront when you know the final size.

The Problem with Growing On-Demand

By now you understand that ArrayList grows automatically as you add elements, occasionally triggering expensive resize operations that copy the entire backing array. But what if you already know you'll need space for 10,000 elements? Why suffer through multiple resizes when you could allocate the right amount of space from the start?

Two Ways to Pre-Size

Using the Initial Capacity Constructor

When creating your ArrayList, specify the expected size:

ArrayList<String> names = new ArrayList<>(10000);

This allocates an internal array with capacity for 10,000 elements immediately. No resizes will occur until you exceed that threshold.

Using ensureCapacity on an Existing List

If you already have an ArrayList but know you're about to add many elements:

ArrayList<Integer> numbers = new ArrayList<>();
numbers.ensureCapacity(5000);
// Now add 5000 elements with zero resizes

The ensureCapacity(int minCapacity) method grows the backing array to at least the specified capacity if it's not already large enough.

Real-World Analogy

Imagine you're hosting a dinner party. You could set the table one place setting at a time, rearranging chairs each time someone new confirms (resizing). Or you could count RSVPs upfront and set all 12 places at once (pre-sizing). The second approach saves repeated work.

When to Pre-Size

Pre-sizing makes sense when:

  • You know the approximate final size before adding elements
  • You're adding many elements in a loop
  • Performance matters and you want predictable, fast insertion

Key Takeaway: When you know your ArrayList's final size upfront, use the initial capacity constructor or ensureCapacity() to avoid all resize operations, making every add() genuinely O(1).