ArrayList in Java
Compare ArrayList's Java SE 27 contract with OpenJDK 27 growth behavior, capacity hints, operation costs, fail-fast iterators, and bounded concurrency options.
Compare ArrayList's Java SE 27 contract with OpenJDK 27 growth behavior, capacity hints, operation costs, fail-fast iterators, and bounded concurrency options.
ArrayList in Java
ArrayList<E> is a resizable implementation of List<E>. It keeps elements in order and supports constant-time indexed reads and writes. Appending is amortized constant time; inserting or removing at an index can shift the elements that follow it.
Introduction
The Java SE 27 API documents constant-time get() and set() and amortized constant-time appends. Inserting or removing at an index can take linear time because the elements after it shift.
size() is the number of stored elements. Capacity is the size of the internal array, but ArrayList has no public capacity() method. The API specifies an initial capacity of ten for the no-argument constructor and lets you request capacity with a constructor or ensureCapacity(). It does not specify a growth formula. If you know roughly how many elements you will add, an initial-capacity hint can reduce reallocations; it does not change the list’s logical size().
ArrayList is unsynchronized. If multiple threads access it and at least one structurally modifies it, coordinate access with external synchronization or choose a collection designed for the access pattern. A fail-fast iterator may throw ConcurrentModificationException when it notices a change, but that check is best-effort bug detection, not a concurrency guarantee. For producer/consumer work with a fixed backlog limit, a bounded ArrayBlockingQueue can be a better fit than a shared list.
When to Use ArrayList
Use ArrayList when:
- You need a resizable ordered collection with O(1) random access
- You primarily add/get elements by index and seldom insert/delete in the middle
- You want to store object references with generics for compile-time type safety
- You need to pass collections between APIs that expect
List
Do not use ArrayList when:
- You often insert or remove near the beginning and can work through a positioned iterator (consider
LinkedList) - You need queue or stack operations at the ends (consider
ArrayDeque; aLinkedListcan also help when updates use a positioned iterator) - You need primitive-specific collections without boxing (use primitive collections libraries)
- Multiple threads exchange work items through a bounded producer/consumer queue (use a queue such as
ArrayBlockingQueuewhen those semantics fit)
Internal Structure
ArrayList stores references in an internal array and tracks the logical size separately. Capacity is the number of available slots. The API does not expose it directly or promise a particular growth policy.
OpenJDK 27 implementation note
This paragraph describes one implementation, not a Java API guarantee. In the OpenJDK 27 update source, growth requests a preferred increase of oldCapacity >> 1 (about half the current capacity). ArraysSupport.newLength also considers the minimum capacity required and array-size limits. Treat that as an implementation detail: other JDK builds or releases may choose different capacities. The stable contract is that appending is amortized constant time, as stated in the Java SE 27 API.
Mermaid Diagram: ArrayList Resize Operation
sequenceDiagram
participant Client
participant AL as ArrayList
participant Array as Internal Array
Client->>AL: add(element) at full capacity
AL->>AL: allocate a larger array (implementation detail)
AL->>Array: System.arraycopy(oldArray, newArray)
Array-->>AL: elements copied
AL->>AL: add new element
AL-->>Client: element added
Failure Scenarios
| Scenario | Cause | Result |
|---|---|---|
IndexOutOfBoundsException |
Index is less than zero or at least size() |
The requested list index is invalid |
ConcurrentModificationException |
A fail-fast iterator detects an unexpected change | Best-effort bug signal |
ClassCastException |
Retrieving an element and casting it incorrectly | Runtime exception |
| Capacity exhaustion | The implementation cannot allocate a required array | Allocation may fail with OutOfMemoryError |
Trade-Off Table
| Aspect | Array | ArrayList |
|---|---|---|
| Resizing | Fixed length | Grows as needed |
| Generic type | No generic array types | Yes (ArrayList<T>) |
| Primitive values | Supported, such as int[] |
Wrapper types, such as Integer |
| Random access | O(1) | O(1) |
| Insertion at middle | O(n) | O(n) |
| Memory overhead | Length fixed after allocation | May reserve unused capacity |
| Thread safety | None | Operations are unsynchronized |
Code Snippets
Basic Operations
The main operations have different costs. Appending with add(element) is amortized O(1). add(index, element) shifts later elements and takes O(n); set(index, element) replaces an element in O(1); remove(index) shifts later elements left and takes O(n).
get(index) and size() are O(1). contains(element) scans the list and takes O(n). If membership checks dominate a large workload, a HashSet may help, at the cost of extra memory and without preserving list order.
import java.util.ArrayList;
import java.util.List;
class ArrayListBasics {
public static void main(String[] args) {
List<String> tasks = new ArrayList<>();
tasks.add("Review PR");
tasks.add(0, "Standup");
tasks.set(1, "Code Review");
tasks.add("Run tests");
System.out.println(tasks.get(2));
System.out.println(tasks.size());
System.out.println(tasks.contains("Standup"));
}
}
Save this as ArrayListBasics.java, then run javac ArrayListBasics.java && java ArrayListBasics:
Run tests
3
true
Iterating Safely
ArrayList iterators are fail-fast. They may throw ConcurrentModificationException after an unexpected structural change, such as removing an item directly from the list during iteration. The check is best-effort and exists to help detect bugs. It is not guaranteed to notice every concurrent change, and it does not make the list safe to share between threads.
An enhanced for loop uses an iterator. If you need to remove the current element, call it.remove() on that iterator instead of calling list.remove() directly.
When removing elements that match a condition, use the iterator’s remove() method or removeIf(). Both keep the iteration logic inside the collection API: tasks.removeIf(task -> task.isEmpty());
// Safe: use iterator's remove
for (Iterator<String> it = tasks.iterator(); it.hasNext();) {
String task = it.next();
if (task.startsWith("Review")) {
it.remove(); // updates expected modCount — no ConcurrentModificationException
}
}
// Safe: copy to array first if modifying during for-each
// The copy has its own independent iterator, so remove on original is safe
for (String task : new ArrayList<>(tasks)) {
tasks.remove(task);
}
// Cleanest: removeIf with a predicate
tasks.removeIf(task -> task.isEmpty() || task.startsWith("Draft"));
Sharing data between threads
An ArrayList does not synchronize its operations. If threads must share one mutable list, protect all access with the same lock; wrapping it with Collections.synchronizedList() only helps when callers consistently use the wrapper and synchronize during iteration. For a producer/consumer workflow, use a queue with a defined capacity instead of sharing a general-purpose list. ArrayBlockingQueue is bounded, and its put() and take() methods wait when the queue is full or empty. See the Java SE 27 BlockingQueue contract.
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
class WorkQueueExample {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> work = new ArrayBlockingQueue<>(128);
work.put("job-1"); // waits for space if the queue is full
String job = work.take(); // waits for an item if the queue is empty
System.out.println(job);
}
}
Trim and Capacity Hints
trimToSize() and ensureCapacity() are API methods that can request changes to internal storage. trimToSize() asks the list to reduce its capacity to its current size. This can be useful after building a large list that will not grow again, but trimming also has a cost and is rarely useful during normal incremental updates.
ensureCapacity(int minCapacity) requests room for at least the given number of elements without changing size(). Use it when you know the approximate final element count, such as before loading a pre-counted result set. It may reduce incremental reallocations, but exact allocation behavior is an implementation detail.
Neither method changes the logical size of the list. size() still returns the element count; capacity is an implementation detail. Avoid calling trimToSize() repeatedly on a growing list because each trim may require another allocation and copy.
ArrayList<String> large = new ArrayList<>(1000);
large.addAll(hugeDataset);
large.trimToSize(); // Reduce backing array to exact size before serialization
Observability Checklist
- Use an initial-capacity hint when the expected element count is known
- Log list size distributions to identify unbounded growth patterns
- Treat
ConcurrentModificationExceptionas a bug signal, not a concurrency control mechanism - Use JFR (Java Flight Recorder) to detect excessive GC pressure from frequent resizing
- Review
.contains()calls in hot paths; each call scans the list
Security Notes
ArrayListis unsynchronized; protect shared structural mutations with a common lock or use a collection whose concurrency semantics fit the workload- When storing sensitive data, remember that resizing does not erase the old array before it becomes eligible for garbage collection
- Consider using
Collections.unmodifiableList()to prevent accidental mutation of returned lists - Deserialization of untrusted
ArrayListpayloads can trigger DoS via excessive capacity allocation
Common Pitfalls / Anti-Patterns
- Initial capacity: the API specifies an initial capacity of ten for
new ArrayList<>(); a hint can help when the expected size is large - Subtracting from size during iteration:
tasks.remove(tasks.size() - 1)before iterating backwards is safe; forward iteration with removal requires an iterator - Confusing
size()and capacity:size()is the element count; capacity is the internal array length and has no public getter nullelements:ArrayListallowsnull;List.of()does not- Autoboxing overhead:
ArrayList<Integer>stores boxed references; primitive arrays or primitive collections avoid that boxing
Quick Recap Checklist
- Use
ArrayListwhen you need ordered elements and indexed access; expect shifts for inserts or removals in the middle - Treat append as amortized constant time and the exact growth policy as unspecified
- Set an initial capacity or call
ensureCapacity()when you can estimate a large final size - Use the iterator’s
remove()orremoveIf()for in-place filtering - Protect shared mutations with one synchronization strategy, or use a bounded queue for producer/consumer traffic
Interview Questions
Further Reading
- Java SE 27
ArrayListdocumentation: API behavior, complexity, and capacity methods - Java SE 27
BlockingQueuedocumentation: bounded producer/consumer queue operations - Baeldung:
ArrayListvsLinkedList: performance comparison and trade-offs - Understanding ArrayList capacity and size: a secondary explanation of internal storage
- Effective Java, Item 26: favor generic lists over arrays
- Array Basics: fixed-size array fundamentals before moving to resizable lists
- LinkedList: doubly-linked list implementation for frequent insert/delete
- HashMap: hash-based key-value storage, often used alongside ArrayList
Conclusion
ArrayList provides constant-time indexed reads and amortized constant-time appends through the List API. Inserts and removals in the middle shift later elements. The exact capacity growth remains an implementation detail, and shared mutation needs an explicit concurrency strategy.
If you can estimate a large final size, set an initial capacity or call ensureCapacity() to reduce incremental reallocations. For producer/consumer work with a bounded backlog, use a bounded queue such as ArrayBlockingQueue when queue semantics fit.
For a refresher on fixed-length storage, see Array Basics. If you often change a list through an iterator already at the right position, compare the trade-offs in LinkedList.
Category
Related Posts
Abstract Classes in Java: Interfaces and Composition
Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.
Arithmetic Operators in Java: Division, Overflow, Promotion
Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.
Java Array Basics: Length, Bounds, Copies, and Resizing
Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.