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

ensureCapacity: Triggering Array Growth

Learn when and how ArrayList checks if the backing array has room before adding elements.

ensureCapacity: Triggering Array Growth

What you'll learn: How ArrayList automatically checks and expands its backing array when it runs out of room.

The Automatic Safety Check

Remember that ArrayList stores elements in an internal Object[] array with a fixed size (its capacity). When you call add(), the list doesn't just blindly append the element—it first checks whether there's room. If size equals the current capacity, the backing array is full and needs to grow before the new element can be added.

How It Works

Before every add() operation, ArrayList internally calls a method conceptually similar to ensureCapacity(). This method compares the current size (how many elements are stored) with the array's capacity (how many slots exist). If they're equal, the list allocates a new, larger array, copies all existing elements over, and updates its internal reference to use the new array.

The growth strategy: Typically, the new capacity is about 1.5× the old capacity (the exact formula varies by Java version). So if you have a capacity of 10 and need to grow, the new capacity becomes around 15.

The Analogy

Think of a parking lot with 10 spaces (capacity = 10). You've parked 10 cars (size = 10). When car #11 arrives, you can't just squeeze it in—you need to build a bigger lot (say, 15 spaces), move all 10 cars to the new lot, then park the 11th car.

Why This Matters

This growth happens automatically and transparently. You never see it as a user of ArrayList, but it's crucial for understanding performance: frequent growth operations (allocating and copying) can be expensive if you add many elements to a small initial capacity.

Key Takeaway: ArrayList automatically checks capacity before each add(), triggering array reallocation and copying when size equals capacity, typically growing by about 50% each time.