The ArrayList.ensureCapacity(int minCapacity) method expands the internal Object[] backing array in a single allocation so the list can hold at least minCapacity elements without intermediate resizing copies.
Capacity vs. Size: Calling ensureCapacity() only grows the hidden buffer before bulk add() or addAll() operations; it never changes the logical ArrayList.size(). To shrink unused slack capacity after loading finishes, pair it with ArrayList.trimToSize().
Declared as a public method on java.util.ArrayList<E> (not part of the List interface):
// Increases the capacity of this ArrayList instance, if necessary, to hold at least minCapacity elements
public void ensureCapacity(int minCapacity)
| Element | Type / Value | Internal Behavior |
|---|---|---|
minCapacity |
int |
Desired minimum length of the internal Object[] elementData array. |
| Return Type | void |
Reallocates the internal array via Arrays.copyOf() if minCapacity > currentCapacity. |
| Growth Formula | max(minCap, 1.5 * oldCap) |
Grows by at least 50% (oldCap + (oldCap >> 1)) or directly to minCapacity if larger. |
When an ArrayList is already created and you know several new elements are about to be added via add(), calling ensureCapacity() expands the buffer in one step:
import java.util.ArrayList;
ArrayList<Integer> marks = new ArrayList<Integer>(3);
marks.add(55);
marks.add(54);
marks.add(60);
marks.ensureCapacity(8); // Expand internal array in one step before adding more
marks.add(61);
marks.add(62);
System.out.println("Marks: " + marks);
ArrayList<String> languages = new ArrayList<String>(3);
languages.add("Java");
languages.add("PHP");
languages.add("Python");
languages.ensureCapacity(5);
languages.add("HTML");
System.out.println("Languages: " + languages);Terminal Output:
Marks: [55, 54, 60, 61, 62]
Languages: [Java, PHP, Python, HTML]
A common misconception is that ensureCapacity(100) creates 100 accessible elements. In reality, capacity is the length of the hidden storage array, whereas size() is the count of elements actually added. Calling get(0) or set(0, val) on an empty list after ensureCapacity(100) still throws an IndexOutOfBoundsException:
ArrayList<String> buffer = new ArrayList<>();
buffer.ensureCapacity(100); // Pre-allocates Object[100], but logical size() is still 0!
System.out.println("Logical size after ensureCapacity(100): " + buffer.size());
try {
buffer.get(0); // Throws IndexOutOfBoundsException because size is 0!
} catch (IndexOutOfBoundsException ex) {
System.out.println("Caught on get(0): " + ex.getMessage());
}Terminal Output:
Logical size after ensureCapacity(100): 0
Caught on get(0): Index 0 out of bounds for length 0
ensureCapacity(minCapacity) never shrinks an ArrayList. If minCapacity is less than or equal to the current capacity (or negative, or <= 10 on a default-constructed new ArrayList<>()), the method returns immediately without copying memory:
ArrayList<String> list = new ArrayList<>(); // Default lazy capacity is 10
list.add("A"); // Allocates Object[10]
list.ensureCapacity(5); // No-op: 5 <= current capacity 10
list.ensureCapacity(-3); // No-op: negative minCapacity is ignored
System.out.println("List unchanged: " + list + " (size=" + list.size() + ")");Terminal Output:
List unchanged: [A] (size=1)
Without ensureCapacity(), adding 1,000 elements one by one triggers 12 separate array allocations and copies as the capacity steps up by 1.5x each time. Calling ensureCapacity(1000) performs just 1 allocation of exact size 1000:
int cap = 10, resizes = 0;
while (cap < 1000) { cap = cap + (cap >> 1); resizes++; }
System.out.println("Default 1.5x resizes: " + resizes + " | ensureCapacity(1000): 1");Terminal Output:
Default 1.5x resizes: 12 | ensureCapacity(1000): 1
How to manage capacity at construction, before bulk loads, and after filtering:
| Method / Constructor | Affects size()? | When to Use |
|---|---|---|
new ArrayList<>(initialCap) |
No (size = 0) |
Best when total expected count is known when creating the list. |
list.ensureCapacity(minCap) |
No (Unchanged) | Best when expanding an already existing list before a batch loop. |
list.trimToSize() |
No (Unchanged) | Shrinks backing array down to exact size() to free unused heap memory. |
Reserving dest.size() + count before appending each incoming batch guarantees at most one array resize per chunk:
public class ChunkLoader {
public static void appendChunk(ArrayList<Integer> dest, int count, int start) {
dest.ensureCapacity(dest.size() + count);
for (int i = 0; i < count; i++) dest.add(start + i);
}
public static void main(String[] args) {
ArrayList<Integer> data = new ArrayList<>(2);
appendChunk(data, 3, 10);
System.out.println("Loaded: " + data);
}
}Terminal Output:
Loaded: [10, 11, 12]
Combining ensureCapacity() before a filtered ingestion loop with trimToSize() afterward gives fast insertion and minimal memory footprint:
public class ExpandAndCompact {
public static void main(String[] args) {
ArrayList<Integer> evens = new ArrayList<>();
evens.ensureCapacity(100); // 1. Pre-size for up to 100 candidates
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) evens.add(i);
}
evens.trimToSize(); // 2. Reclaim unused 95 slots after filtering
System.out.println("Compacted evens (" + evens.size() + "): " + evens);
}
}Terminal Output:
Compacted evens (5): [2, 4, 6, 8, 10]
If you need a list of n pre-populated slots so you can assign to arbitrary indices with list.set(i, val), ensureCapacity(n) will not work because size() remains 0. Use new ArrayList<>(Collections.nCopies(n, null)) instead.
Because ensureCapacity() is specific to the array-backed implementation of ArrayList, it is not defined on the java.util.List interface. Declare the variable as ArrayList<E> or pass the capacity to the constructor new ArrayList<>(cap).
Compile and run this verification class in any Java environment:
public class ArrayListEnsureCapacityFullDemo {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.ensureCapacity(50);
if (list.isEmpty() && list.size() == 0) {
System.out.println("Check 1 Passed: ensureCapacity(50) kept size() at 0.");
}
ArrayList<String> prefilled = new ArrayList<>(Collections.nCopies(4, "INIT"));
prefilled.set(2, "UPDATED");
if (prefilled.size() == 4 && prefilled.get(2).equals("UPDATED")) {
System.out.println("Check 2 Passed: Collections.nCopies pre-fills logical slots.");
}
System.out.println("All ArrayList.ensureCapacity() verification checks passed!");
}
}Terminal Output:
Check 1 Passed: ensureCapacity(50) kept size() at 0.
Check 2 Passed: Collections.nCopies pre-fills logical slots.
All ArrayList.ensureCapacity() verification checks passed!
ArrayList does not expose a public capacity() getter (only size() is public) because capacity is an internal storage detail managed automatically.
Not for a single addAll(c) call, because addAll() automatically calculates and allocates the required capacity in one step. Only call ensureCapacity() when you are about to run multiple add() or addAll() calls in a loop.
Yes, in OpenJDK ArrayList, calling ensureCapacity() when it triggers an internal array growth increments modCount.
Up to Integer.MAX_VALUE - 8 (approximately 2.14 billion elements), subject to available JVM heap memory.
size().ArrayList methods.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.