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

The add Operation: Common Case Without Resize

How adding an element works when capacity is sufficient—simply storing at the next index.

The add Operation: Common Case Without Resize

What you'll learn: How ArrayList adds an element when there's already room in the internal array—the fast, simple path.

The Happy Path

When you call add() on an ArrayList and there's sufficient capacity, the operation is beautifully simple. No new arrays are created, no copying happens—just a direct assignment.

Think of it like adding a book to a bookshelf that still has empty slots. You simply place the book in the next available space and update your count. No furniture moving required.

How It Works Step-by-Step

When size < capacity:

  1. Store the element at index size in the backing array
  2. Increment size by 1
  3. Return true to indicate success

That's it! The element goes directly into the next available slot.

Why This Is Fast

This common case is O(1) constant time—one of the fastest operations possible. The ArrayList simply:

  • Accesses the array at a known index (size)
  • Assigns the new element
  • Increments a counter

No loops, no copying, no memory allocation. It's as efficient as storing a value in a regular array.

The Capacity Check

Before performing this simple assignment, add() checks whether size == capacity. If there's room (size is less than capacity), it takes this fast path. If not, it triggers the resize operation you learned about previously—but most of the time, especially with proper initial sizing, you hit this optimized path.

Key Takeaway: When an ArrayList has sufficient capacity, adding an element is simply storing it at the next index and incrementing size—a constant-time operation with no overhead.