ArrayList Capacity and Size in Java
The ArrayList
is a fundamental data structure in Java, providing a dynamic array implementation. However, a common point of confusion arises from the difference between its capacity and its size. Understanding this distinction is crucial for writing efficient and predictable code.
What is Size?
The size of an ArrayList
represents the number of elements currently stored within it. This is what you get when you call the size()
method on the ArrayList
object. It reflects how many meaningful values are actively being held. Initially, when you create an empty ArrayList
, its size is zero. As you add elements using the add()
method, the size increases.
What is Capacity?
The capacity of an ArrayList
refers to the amount of storage space allocated for the elements it can hold without needing to reallocate its internal array. Think of it as the physical size of the underlying array. When you add elements beyond the current capacity, the ArrayList
automatically creates a new, larger array, copies the existing elements, and then adds the new element. This reallocation process can be computationally expensive.
Setting Initial Capacity
You can control the initial capacity when you create an ArrayList
using a constructor that accepts an integer argument:
ArrayList<Integer> arr = new ArrayList<>(10);
This creates an ArrayList
with an initial capacity of 10. However, it’s important to note that the size of the ArrayList
remains zero at this point. You haven’t added any elements yet.
Why Set Initial Capacity?
Setting an initial capacity can improve performance, especially if you know in advance how many elements you’ll be storing in the ArrayList
. By providing a reasonable initial capacity, you reduce the number of times the ArrayList
needs to reallocate its internal array as you add elements. This can save significant processing time and memory usage, particularly for large lists.
Common Misconceptions and Errors
A frequent error occurs when trying to directly access elements at indices beyond the current size of the ArrayList
, even if the capacity is sufficient.
ArrayList<Integer> arr = new ArrayList<>(10);
//arr.add(5, 10); // This will throw an IndexOutOfBoundsException
arr.add(0, 10); // Correct way to add to the list
The add(int index, Object element)
method inserts the element at the specified index, shifting existing elements to make room. Attempting to add an element at an index beyond the current size of the list is invalid.
Example: Initializing and Populating an ArrayList
Here’s a practical example demonstrating how to set the initial capacity and populate an ArrayList
:
import java.util.ArrayList;
public class ArrayListCapacity {
public static void main(String[] args) {
// Create an ArrayList with an initial capacity of 5
ArrayList<String> names = new ArrayList<>(5);
// Add some names to the list
names.add("Alice");
names.add("Bob");
names.add("Charlie");
System.out.println("Size: " + names.size()); // Output: Size: 3
//The capacity can be greater than the size
// To check capacity, you need to use reflection which is beyond the scope of this tutorial
// Iterate through the list and print the names
for (String name : names) {
System.out.println(name);
}
}
}
Alternatives for Pre-Sized Lists
If you require a list with a fixed size and pre-populated with default values, consider these alternatives:
-
Arrays.asList()
: Creates a fixed-size list backed by an array.List<Integer> fixedList = Arrays.asList(new Integer[10]);
-
Collections.nCopies()
: Creates a fixed-size list with a specified number of copies of a given object.ArrayList<Integer> repeatedList = new ArrayList<>(Collections.nCopies(10, 0));
-
Collections.fill()
: Fills an existing list with a specified object.