- Prerequisites
- 4.2 List Implementations · 3.3 Restrictions (generic arrays)
- Covers
- Backing array · Capacity · Growth · Random access
- Related
- 6.1 Iterator (modCount) · Book 2 (memory, arrays)
On this page
1Concept / Definition
ArrayList is a resizable array. It keeps elements in an Object[] elementData and a size counter; the array is usually larger than size, and when it fills up, ArrayList allocates a bigger one and copies the elements across. Everything about its performance follows from this simple structure.

2Why It Exists
A Java array has a fixed length chosen when it is created, but most programs do not know in advance how many elements they will collect: rows from a query, lines of a file, items in a cart. Before Java 1.2 the answer was Vector, which grew the same way but synchronised every method. ArrayList keeps the array's strengths, contiguous storage and constant-time indexing, adds automatic growth, and leaves thread safety to the caller.
The interesting part is the growth policy. Growing by a fixed amount would make n appends cost O(n²) copies; growing by a factor makes them O(n) in total. The factor 1.5 trades a little more copying for less unused memory than doubling, which is why the internals of this one class explain so much about allocation rates and memory use in real services.
3Core Concepts
Backing array
The field transient Object[] elementData holds references to the elements; element objects live elsewhere on the heap. The array is Object[] because generic arrays cannot be created (3.3); get casts elements to E. A new ArrayList<>() starts with a shared empty array and allocates 10 slots on the first add, so empty lists cost almost nothing.
Capacity
Capacity is elementData.length, the number of elements the list can hold before growing. It is not visible through the List API, but it can be set with new ArrayList<>(initialCapacity), raised with ensureCapacity(n) and reduced to size with trimToSize(). Setting it appropriately avoids repeated copying while building large lists.
Growth
When an add finds the array full, ArrayList computes a new capacity of oldCapacity + (oldCapacity >> 1) — about 1.5 times — (or more, if more is needed), allocates it with Arrays.copyOf and copies the references. Each growth is O(n), but because the capacity grows geometrically, the total copying over n adds is proportional to n, so add at the end is amortised O(1).

Inserting or removing anywhere but the end shifts all subsequent elements with System.arraycopy, an O(n − index) operation implemented as a fast memory move. Removing from the end is O(1). ArrayList never shrinks automatically.

Random access
get(i) and set(i, e) are a bounds check plus an array access — O(1). ArrayList implements the RandomAccess marker, so algorithms use indexed loops on it. Because references are contiguous, iteration is also CPU-cache friendly, which is the main reason ArrayList beats LinkedList in practice even where their Big-O is similar.
4How It Works Internally
// Simplified from OpenJDK java.util.ArrayList
public boolean add(E e) {
modCount++; // for fail-fast iterators (6.1)
if (size == elementData.length) elementData = grow(size + 1);
elementData[size++] = e;
return true;
}
private Object[] grow(int minCapacity) {
int oldCapacity = elementData.length;
int newCapacity = ArraysSupport.newLength(oldCapacity,
minCapacity - oldCapacity, // minimum growth
oldCapacity >> 1); // preferred growth: +50%
return elementData = Arrays.copyOf(elementData, newCapacity);
}
@SuppressWarnings("unchecked")
public E get(int index) {
Objects.checkIndex(index, size);
return (E) elementData[index];
}remove sets the vacated last slot to null so the removed object can be garbage-collected. modCount counts structural modifications; iterators compare it to detect concurrent modification (6.1). subList returns a view sharing the same array.
5APIs / Features / Syntax
Most of ArrayList's API is the List interface. The methods below are the ones that interact with its internals, capacity and the backing array:
| API | Effect on the backing array | Cost |
|---|---|---|
| new ArrayList<>() | Shared empty array; 10 slots on the first add | O(1) |
| new ArrayList<>(n) | Array of exactly n slots, size 0 | O(n) allocation |
| new ArrayList<>(collection) | Copy of collection.toArray() | O(n) |
| ensureCapacity(n) | Grows once to at least n before a bulk load | O(size) |
| trimToSize() | Copies into an array of exactly size slots | O(size) |
| add(e) / add(i, e) | Writes a slot; may grow; add(i, e) shifts the tail | amortised O(1) / O(n - i) |
| remove(i) / removeIf(p) | Shifts the tail and nulls the freed slot / one compaction pass | O(n - i) / O(n) |
| addAll(i, c) | One shift of the tail for the whole collection | O(n + m) |
| subList(a, b) | A view on the same array, no copy | O(1) |
| toArray() | A new array: the list stays independent | O(n) |
Collections.nCopies(n, x) and new ArrayList<>(Collections.nCopies(n, x)) are the idiomatic way to get a list that already has n elements, which new ArrayList<>(n) does not (section 7).
6Practical Examples
Example 1 — Using ArrayList efficiently
Problem. A billing job converts rows to invoices, publishes an immutable result, drops void invoices and puts a batch of new ones at the front. Each step can cost O(n) or O(n²) depending on the call used.
// Pre-size when the size is known
List<Invoice> invoices = new ArrayList<>(rows.size());
for (Row r : rows) invoices.add(Invoice.from(r));
// Build then freeze: trim, or better, make immutable (7.1)
List<Invoice> result = List.copyOf(invoices);
// Removing many elements: removeIf is O(n); remove(i) in a loop is O(n²)
invoices.removeIf(Invoice::isVoid);
// Bulk insert at the front: one shift instead of many
invoices.addAll(0, newInvoices);Example 2 — Mini program: replaying the growth policy
Problem. How much copying does "amortised O(1)" really mean, and how much of the array is unused at the end? Capacity is not visible through the API, so the program replays ArrayList's arithmetic for lists built one add at a time.
import java.util.*;
public class GrowthTrace {
// ArrayList's arithmetic: 10 slots on the first add, then old + old / 2
static int next(int capacity, int needed) {
if (capacity == 0) return Math.max(10, needed);
return Math.max(capacity + (capacity >> 1), needed);
}
static void build(int n) {
int capacity = 0, grows = 0;
long copied = 0;
List<Integer> seq = new ArrayList<>();
for (int size = 0; size < n; size++) { // add one element
if (size == capacity) {
copied += size; // Arrays.copyOf moves size refs
capacity = next(capacity, size + 1);
grows++;
if (seq.size() < 8) seq.add(capacity);
}
}
if (n == 1_000) System.out.println("capacities " + seq + " ...");
System.out.printf("n=%,11d grows=%2d copies/add=%.2f unused=%4.1f%%%n",
n, grows, (double) copied / n, 100.0 * (capacity - n) / capacity);
}
public static void main(String[] args) {
for (int n : new int[] {10, 100, 1_000, 1_000_000, 10_000_000}) build(n);
System.out.println("new ArrayList<>(1_000_000): one array, no copies");
}
}n= 10 grows= 1 copies/add=0.00 unused= 0.0%
n= 100 grows= 7 copies/add=2.02 unused= 8.3%
capacities [10, 15, 22, 33, 49, 73, 109, 163] ...
n= 1,000 grows=13 copies/add=2.46 unused=19.0%
n= 1,000,000 grows=30 copies/add=2.43 unused=17.7%
n= 10,000,000 grows=36 copies/add=2.77 unused=27.8%
new ArrayList<>(1_000_000): one array, no copies
Why it behaves this way. Each growth copies every element so far, but the next growth comes only after 50% more adds, so the copies form a geometric series: between about 2 and 3 references copied per element added, whatever n is (Figure 4). Ten million adds need only 36 growths. The unused part depends on where n falls between two capacities and can reach a third of the array, which is the slack that trimToSize() or List.copyOf removes. A pre-sized list allocates once and copies nothing, and the discarded arrays of all those growths are garbage the collector must handle.
Example 3 — A list holds references: copies are shallow
Problem. A service copies a list of accounts with new ArrayList<>(live) before reporting, and the report still shows a balance changed after the copy was taken.
import java.util.*;
public class SharedReferences {
static final class Account { // a mutable element type
final String id; long balance;
Account(String id, long balance) { this.id = id; this.balance = balance; }
@Override public String toString() { return id + "=" + balance; }
}
public static void main(String[] args) {
List<Account> live = new ArrayList<>(List.of(new Account("a1", 100),
new Account("a2", 250)));
List<Account> copy = new ArrayList<>(live); // new array, same objects
List<Account> frozen = List.copyOf(live); // immutable, same objects
live.get(0).balance -= 40; // change an element
live.add(new Account("a3", 10)); // change the list
System.out.println("live " + live);
System.out.println("copy " + copy);
System.out.println("frozen " + frozen);
System.out.println("same object: " + (copy.get(0) == live.get(0)));
}
}live [a1=60, a2=250, a3=10]
copy [a1=60, a2=250]
frozen [a1=60, a2=250]
same object: true
Why it behaves this way. The backing array holds references (section 3), and both the copy constructor and List.copyOf copy those references into a new array, not the objects. Adding a3 changes only live's array, but the balance change happens inside an Account that all three lists point to (Figure 5). Immutable element types, such as records, make shallow copies safe; with mutable elements a snapshot needs copies of the elements too.
Example 4 — Removing half a list: a shift per removal, or one pass
Problem. Example 1 claims that remove(i) in a loop is O(n²) and removeIf O(n). Remove the even numbers from a list of 200,000 both ways; the loop runs backwards, so it is at least correct.
import java.util.*;
public class BulkRemoveCost {
static List<Integer> numbers(int n) {
List<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; i++) list.add(i);
return list;
}
public static void main(String[] args) {
int n = 200_000;
for (int round = 0; round < 2; round++) { // round 0 warms up
List<Integer> a = numbers(n);
long t0 = System.nanoTime();
for (int i = a.size() - 1; i >= 0; i--) // backwards: correct,
if (a.get(i) % 2 == 0) a.remove(i); // but shifts each time
long loop = (System.nanoTime() - t0) / 1_000_000;
List<Integer> b = numbers(n);
t0 = System.nanoTime();
b.removeIf(x -> x % 2 == 0); // one compaction pass
long once = (System.nanoTime() - t0) / 1_000_000;
if (round == 1) {
System.out.println("remove(i) loop: " + loop + " ms, removeIf: "
+ once + " ms");
System.out.println("same result : " + a.equals(b)
+ ", size " + b.size());
}
}
}
}remove(i) loop: 428 ms, removeIf: 10 ms
same result : true, size 100000Why it behaves this way. Each remove(i) moves every element after i one slot left with System.arraycopy; 100,000 removals move about 5 billion references in total, quadratic work even though each copy is fast. removeIf first marks the elements to remove, then moves each survivor once to its final slot and nulls the tail: one pass, typically one to two orders of magnitude faster, and the gap widens with the size of the list.
7Common Problems & Mistakes
| Mistake | Consequence | Better approach |
|---|---|---|
| Removing elements by index in a forward loop | The shifted neighbour is skipped, and each removal shifts the tail: wrong and O(n²) | removeIf, or Iterator.remove (4.2) |
| Repeated add(0, x) on a large list | Every insert shifts the whole list: O(n) each, O(n²) for the loop | ArrayDeque.addFirst, or append then Collections.reverse, or addAll(0, batch) once |
| Holding a small subList of a huge list | The view keeps the entire backing array, and the list object, reachable | Copy it: new ArrayList<>(list.subList(a, b)) or List.copyOf(...) |
| Long-lived lists that grew large and then shrank | ArrayList never shrinks: the array keeps its peak capacity | trimToSize(), or replace the list with a copy |
| Assuming new ArrayList<>(n) contains n elements | It is empty with capacity n: get(0) and set(0, x) throw IndexOutOfBoundsException | new ArrayList<>(Collections.nCopies(n, x)), or add the elements |
| Treating a list copy as a snapshot of mutable elements | Copies share the element objects; later changes show in every copy (Example 3) | Immutable elements (records), or copy the elements too |
8Performance & Production Considerations
An ArrayList of n elements uses about 4n bytes of references (with compressed references) plus up to 50% slack, plus the elements. Growth creates garbage arrays that are immediately discarded; for very large lists built in hot paths, pre-sizing measurably reduces allocation and GC pressure. Arrays larger than about half a region size are "humongous" objects in G1 (Book 2), another reason to avoid unnecessarily large capacities.
9Architecture & Design Considerations
ArrayList is the default sequence in Java, so its costs add up across a code base. In request paths, prefer collecting into lists of known size, or streams that end in toList(), which sizes its result; building large lists one element at a time in a hot path creates a steady stream of discarded arrays. For results handed across an API boundary, return an immutable list: it is trimmed, safe to share, and prevents callers from depending on the mutability of your internal list.
For very large or numeric data, the reference-per-element design is itself the problem: a List<Long> of ten million values stores ten million Long objects plus 40 MB of references. Primitive arrays, IntStream, or a primitive collection library, and for large datasets columnar or off-heap storage, are design decisions to make early, before a list type spreads through the signatures of a system.
10Interview Questions & Answers
How does ArrayList store its elements?
In an internal Object[] array plus a size field. Elements are references; the array's length is the capacity.
How does ArrayList grow?
When full, it allocates a new array about 1.5 times larger (old + old >> 1, or more if required) and copies the elements with Arrays.copyOf.
Why is ArrayList.add amortised O(1)?
Growth copies O(n) elements, but because capacity grows geometrically, the total copying across n additions is proportional to n, so the average cost per add is constant.
What is the difference between size and capacity?
Size is the number of elements in the list; capacity is the length of the backing array, i.e. how many elements fit before the next growth.
Why is removing elements in a for loop by index problematic?
After removing index i, later elements shift left, so the loop skips the next element; each removal also shifts the tail, making the whole loop O(n²). removeIf or Iterator.remove handle it correctly and efficiently.
When would you pre-size or trim ArrayLists in a service?
Pre-size when building large lists of known size in hot paths, to avoid repeated copying and garbage. Trim or convert to an immutable copy when a large list becomes long-lived and read-only, to release slack capacity.
What is the initial capacity of new ArrayList<>()?
None is allocated at construction: the list shares an empty array, and the first add allocates 10 slots. After that the capacity grows by half each time it fills: 15, 22, 33 and so on. With new ArrayList<>(n) the array of n slots is allocated at once, which is the better choice when the final size is known.
What does this program print?
import java.util.*;
public class CapacityQuiz {
public static void main(String[] args) {
List<String> names = new ArrayList<>(100);
System.out.println(names.size() + " " + names.isEmpty());
try {
names.set(0, "asha");
} catch (IndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
List<String> filled = new ArrayList<>(Collections.nCopies(3, "-"));
filled.set(0, "asha");
System.out.println(filled);
}
}It prints 0 true, then Index 0 out of bounds for length 0, then [asha, -, -]. The argument 100 is a capacity, not a size: the list is empty, and set(0, ...) is checked against the size, 0, so it throws IndexOutOfBoundsException with the message shown. A list created from Collections.nCopies already has three elements, so set(0, ...) replaces the first.
Why does ArrayList.remove set the freed slot to null?
After the tail is shifted left, the last slot still holds a reference to the element that was there. Without elementData[--size] = null that object would stay reachable through the array, invisible to the list's API and impossible for the garbage collector to reclaim: an obsolete-reference leak. The same rule applies to any array-backed structure you write yourself, such as a stack or a pool.
Is a copy made with new ArrayList<>(list) independent of the original?
The list structure is: adding to or removing from one does not affect the other, because each has its own array. The elements are not: both arrays refer to the same objects, so a change to a mutable element is visible through both lists (Example 3). With immutable elements such as records or strings, the shallow copy is a complete snapshot.
A heap dump of a service shows a few ArrayLists with backing arrays of 50 million slots, mostly null, held by a cache. What happened and how do you fix it?
The lists grew to a peak, for example during a bulk reload, and were then cleared or shrunk; ArrayList never shrinks its array, so each keeps hundreds of megabytes of empty slots. Another possibility is small subList views of big lists kept in the cache. Fix the code that keeps the lists: replace the content with a fresh, right-sized list, or call trimToSize() after the reload, and store copies rather than views. Then add a metric or test for the cache's retained size.
For an in-memory time series of 20 million long timestamps, would you use ArrayList<Long>, long[] or a primitive collection?
ArrayList<Long> costs a 4-byte reference plus a 16-byte Long per value, about 400 MB, and every read unboxes. A long[] costs 8 bytes per value, 160 MB, and is the fastest to scan, but you manage growth yourself. A primitive list from a library such as fastutil gives the long[] layout with ArrayList-style growth and methods. For a fixed dataset, long[]; for one that grows, the primitive list; ArrayList<Long> only for small series.
What guidance would you give teams on building large lists in high-throughput services?
Size lists when the size is known or can be estimated, and prefer stream().toList() or List.copyOf for results. Avoid building multi-million-element lists in request paths: page or stream the data instead. Return immutable lists across boundaries, never share mutable lists between threads without a documented lock, and do not keep views of large lists. Use primitive structures for large numeric data. Check the effect with allocation profiles (JFR) rather than intuition, since list growth shows up as allocation pressure, not as slow code.
After a data volume increase, GC time in a reporting service rises from 2% to 30%, and allocation profiling points at Arrays.copyOf called from ArrayList.grow. What do you change?
The reports build large lists one element at a time, so each list allocates and discards about 30 growing arrays, some large enough to be humongous objects in G1. Pre-size the lists from the known row count, or call ensureCapacity before a bulk load. Where the full list is not needed, stream rows to the output instead of collecting them. Re-measure allocation rate and GC time after each change, and add the data volume to the performance test that missed it.
Test your knowledge on this topic →Flashcards from this topic's 14 questions, filtered by level and type.
Key Takeaways
- ArrayList = Object[] + size; capacity is the array length.
- Grows by ~1.5×; append is amortised O(1).
- get/set O(1); middle insert/remove O(n) via arraycopy.
- Pre-size large lists; use removeIf; beware subList views and leftover capacity.