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

How add() Works: Appending to the End

Trace the internal steps when adding an element, from size check to array assignment and increment.

How add() Works: Appending to the End

What You'll Learn

You'll trace the exact internal steps that happen when you call add() on an ArrayList, from checking space availability to storing the element and updating the size.

The Internal Mechanics of add()

When you call list.add(element) on an ArrayList, several precise steps occur behind the scenes:

Step-by-Step Breakdown

1. Size Check
The ArrayList first checks: "Is my current size equal to my capacity?" (Remember, size is how many elements are stored; capacity is the backing array's length.)

2. Growth Decision

  • If size < capacity: there's room, proceed to step 3
  • If size == capacity: the backing array is full and must be expanded (we'll cover growth mechanics in future lessons)

3. Array Assignment
The element is placed into the backing array at index size. Think of it like this: if you have 5 elements (size = 5), the next one goes to index 5 (the 6th position, since we start counting at 0).

// Conceptually (simplified):
backingArray[size] = element;

4. Size Increment
The size field is incremented by 1 to reflect the new element count.

Analogy

Imagine a parking lot with numbered spaces. The capacity is the total number of spaces. The size is how many cars are parked. When a new car arrives, you check if there's room, park it in the next empty spot (at index size), then update your count.

Key Takeaway:
add() appends to the end by placing the element at index size, then incrementing size—a constant-time O(1) operation when capacity is sufficient.