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.

published: reading time: 15 min read author: Geek Workbench updated: November 20, 2026
Quick Summary

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; a LinkedList can 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 ArrayBlockingQueue when 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 ConcurrentModificationException as 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

  • ArrayList is 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 ArrayList payloads can trigger DoS via excessive capacity allocation

Common Pitfalls / Anti-Patterns

  1. Initial capacity: the API specifies an initial capacity of ten for new ArrayList<>(); a hint can help when the expected size is large
  2. Subtracting from size during iteration: tasks.remove(tasks.size() - 1) before iterating backwards is safe; forward iteration with removal requires an iterator
  3. Confusing size() and capacity: size() is the element count; capacity is the internal array length and has no public getter
  4. null elements: ArrayList allows null; List.of() does not
  5. Autoboxing overhead: ArrayList<Integer> stores boxed references; primitive arrays or primitive collections avoid that boxing

Quick Recap Checklist

  • Use ArrayList when 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() or removeIf() for in-place filtering
  • Protect shared mutations with one synchronization strategy, or use a bounded queue for producer/consumer traffic

Interview Questions

1. How does ArrayList differ from a plain Java array?
A plain array has a fixed length. `ArrayList` implements `List` and can grow as elements are added. It also provides operations such as `add()`, `remove()`, and `contains()`, with generic types for compile-time checks.
2. What is the time complexity of adding an element to an ArrayList?
Appending is amortized O(1). Most appends take constant time; an occasional growth operation takes O(n). Across n appends, the total work is O(n), so the average cost per append is constant.
3. Why should you specify initial capacity for large ArrayLists?
The no-argument constructor has an initial capacity of ten, according to the API. For a large list, `new ArrayList<>(expectedSize)` can reduce reallocations. The exact growth policy is unspecified, so do not assume a particular number of copies.
4. What is ConcurrentModificationException and when does it occur?
A fail-fast iterator may throw it after an unexpected structural change. The check is best-effort bug detection, not a guarantee and not a thread-safety mechanism.
5. When would you choose LinkedList over ArrayList?
Choose `LinkedList` when you already have an iterator at the insertion or removal point and need to update the list there. Finding an arbitrary position still takes linear time, and the linked nodes use more memory. `ArrayList` usually fits indexed reads and appends better.
6. How does ArrayList handle growth when the backing array fills up?
The API promises amortized constant-time append but does not specify a growth formula. In the OpenJDK 27 update source, growth requests a preferred increase of about half the old capacity and uses `ArraysSupport.newLength` to account for required capacity and array limits. That detail can change across implementations or releases.
7. What is the difference between size() and capacity() in ArrayList?
`size()` returns the number of stored elements. Capacity is the internal array length, but standard `ArrayList` has no `capacity()` getter. You can request capacity with the constructor or `ensureCapacity()`; `trimToSize()` asks it to reduce unused space.
8. Does ArrayList allow null elements?
Yes. `ArrayList` permits `null` values. `List.of()` rejects nulls, while `Collections.checkedList()` checks element types but is not a null-rejection policy.
9. How would you implement a thread-safe ArrayList?
For a list shared across threads, use one synchronization strategy consistently or choose a concurrent collection that fits the workload. `CopyOnWriteArrayList` suits read-heavy workloads because writes copy the backing array. A `Collections.synchronizedList()` wrapper synchronizes individual operations; callers must still synchronize on the wrapper while iterating. For producer/consumer work with bounded backlog, consider `ArrayBlockingQueue` instead.
10. What is ensureCapacity() and when should you use it?
`ensureCapacity(int minCapacity)` asks the list to make room for at least that many elements without changing its size. Call it before a large batch when you know the expected count; the method may reduce incremental reallocations.
11. Can you store primitive types directly in an ArrayList?
No. `ArrayList` stores references, so primitive values are boxed into wrapper objects such as `Integer`. For primitive-heavy code, a primitive array or a primitive collection can avoid boxing.
12. How do you remove all elements matching a condition from an ArrayList?
Use the iterator's `remove()` method or `removeIf()` for in-place filtering. Removing directly from the list during a for-each loop may trigger a best-effort `ConcurrentModificationException`.
13. What does ArrayList.toArray(T[] a) do versus toArray()?
`toArray()` returns a new `Object[]`. `toArray(T[] a)` returns an array with the requested runtime component type, reusing the supplied array when it is large enough. On Java 11 and later, `list.toArray(String[]::new)` is another typed option; `list.toArray(new String[0])` works on earlier releases too.
14. How is ArrayList similar to and different from a Java array?
Both support constant-time indexed access. An array has a fixed length; `ArrayList` implements `List` and can grow as elements are added. The list also provides operations such as `contains()`, `indexOf()`, and `remove()`.
15. What is the default capacity of a newly created ArrayList?
The Java SE 27 API specifies an initial capacity of ten. In the OpenJDK 27 implementation, an empty no-argument list initially refers to a shared zero-length placeholder; the first insertion allocates room for ten elements. Later growth follows implementation logic, not a public formula. An initial-capacity argument can help when you expect a large list.
16. How do you make an ArrayList read-only or immutable?
`List.of(...)` creates an immutable list. `Collections.unmodifiableList(list)` blocks changes through the wrapper but reflects changes made through the original list. `Collections.checkedList(list, type)` checks element types on writes. Choose based on whether you need immutability, an unmodifiable view, or runtime type checks.
17. Can ArrayList be used as a stack? What would you use instead?
`ArrayList` can add at the end and remove the last element, but `ArrayDeque` provides stack-oriented `push()`, `pop()`, and `peek()` methods. Use the collection whose API best matches the operations you need.
18. What is the time complexity of contains() and indexOf() in ArrayList?
Both take O(n) because they scan the list. For frequent membership tests, a `HashSet` offers average constant-time lookup, but uses extra memory and does not preserve list order.
19. What is the effect of calling clear() on an ArrayList?
`clear()` removes all elements and sets the size to zero. It does not promise to shrink the internal array. If the list will stay empty and releasing unused storage matters, call `trimToSize()` afterward.
20. How does ArrayList's fail-fast iterator differ from weakly-consistent iterators in other Java collections?
`ArrayList` iterators are fail-fast on a best-effort basis and may throw `ConcurrentModificationException` after an unexpected structural change. `ConcurrentHashMap` iterators are weakly consistent, while `CopyOnWriteArrayList` iterators use a snapshot of the list at iterator creation. Those behaviors have different trade-offs; neither makes `ArrayList` safe for shared mutation.

Further Reading

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.

#java-abstract-classes #java #java-fundamentals

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-arithmetic-operators #java #java-fundamentals

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.

#java-array-basics #java #java-fundamentals