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

ArrayList's Internal Array and Capacity Concept

Understanding how ArrayList uses a backing array and maintains separate size vs capacity values.

ArrayList's Internal Array and Capacity Concept

What you'll learn: How ArrayList manages storage using a hidden array with separate tracking of actual elements versus available space.

The Core Idea

An ArrayList doesn't magically grow as you add elements. Behind the scenes, it stores your data in a regular array (the "backing array"). This array has a fixed length, which is the capacity. However, the size represents how many elements you've actually added, which can be smaller than capacity.

Think of it like a parking lot: capacity is the total number of parking spaces available, while size is the number of cars currently parked. The lot might have 100 spaces (capacity) but only 30 cars (size).

How It Works

When you create an ArrayList, Java allocates an internal array of a certain length. As you add elements, they fill consecutive positions in this array. The ArrayList keeps track of:

  1. The backing array – stores your actual elements
  2. Size – how many elements you've added (what size() returns)
  3. Capacity – the length of the backing array (hidden from you)

For example, if an ArrayList has capacity 10 but you've only added 3 elements, slots 0-2 contain your data, slots 3-9 are empty (usually null), and size() returns 3.

Why This Matters

This separation allows ArrayList to be efficient. You can add elements without creating a new array every time—Java just fills the next available slot. When capacity runs out, the backing array gets replaced with a bigger one, but this happens infrequently.

Key Takeaway: ArrayList uses an internal array (capacity) to store elements, while tracking the actual number of elements separately (size). This dual-tracking enables efficient growth without constant reallocation.