The size vs capacity Distinction
What you'll learn: You'll understand the critical difference between how many elements an ArrayList actually contains versus how much space it has reserved.
Two Different Numbers
When working with ArrayList, there are two separate measurements you need to understand:
- Size: The number of elements currently stored in the list
- Capacity: The length of the underlying array (how many slots are available)
Think of it like a parking lot analogy: size is the number of cars currently parked, while capacity is the total number of parking spaces that exist. The parking lot might have 100 spaces (capacity) but only 15 cars (size).
Why This Matters
When you create an ArrayList, Java allocates an internal array with a certain capacity. As you add elements, the size increases—but the capacity stays the same until the array is full. At that point, Java automatically creates a larger array and copies everything over.
ArrayList<String> list = new ArrayList<>(10); // capacity = 10, size = 0
list.add("Apple"); // capacity = 10, size = 1
list.add("Banana"); // capacity = 10, size = 2
list.add("Cherry"); // capacity = 10, size = 3
You can always check the size with .size(), which returns the actual count of elements. The capacity isn't directly queryable through the public API, but it's always greater than or equal to the size.
The Key Difference
Size changes every time you add or remove an element. Capacity only changes when the underlying array needs to grow (or shrink in some implementations). This distinction is crucial for understanding ArrayList performance and memory usage.
Key Takeaway: Size is how many elements you've stored; capacity is how much room the internal array has allocated. Size ≤ capacity, always.