Java ArrayList vs LinkedList
Compare Java ArrayList and LinkedList operations, indexed access, insertion trade-offs, iteration and deque use with practical examples.
ArrayList and LinkedList both implement Java List, but they store and access data differently. The right choice depends on how your application reads, adds, removes, and iterates over values—not on a rule that one list is always faster.
Java ArrayList vs LinkedList: choose by access and update patterns
ArrayList and LinkedList are two familiar implementations of Java’s List interface. Both preserve insertion order, allow duplicates, support indexed operations, and can store null values. That shared interface is useful because most application code can depend on List<T> rather than a concrete class. Their internal structures, however, are very different, and that changes which operations are cheap.
An ArrayList stores elements in a growable array. A LinkedList stores elements in nodes, where each node refers to its neighbours. The usual lesson is “arrays are good for access; linked lists are good for insertion.” That is a helpful starting point, but it is incomplete. You need to ask where an insertion happens, how you locate that position, how often the list grows, and whether a standard deque is a better fit.
The short decision
| Need | Usually choose | Why |
|---|---|---|
Frequent indexed reads with get(i) | ArrayList | Direct array indexing is fast. |
| Append items and iterate them | ArrayList | Compact storage and cache-friendly iteration. |
| Queue or stack operations at both ends | ArrayDeque | Usually a better specialised deque than LinkedList. |
| Insert/remove at a known iterator position | LinkedList can fit | Link changes are local after the node is reached. |
For most business applications and beginner projects, start with ArrayList. Change only when profiling or a clear access pattern shows a real reason. Choosing an interface first keeps that later change small.
How ArrayList stores elements
An ArrayList keeps references in a contiguous internal array. When you request index 50, Java can calculate the array location directly. This is why get(index) and set(index, value) are generally constant-time operations. The list does not need to walk through earlier elements.
List<String> modules = new ArrayList<>();
modules.add("Variables");
modules.add("Loops");
modules.add("Streams");
String third = modules.get(2); // StreamsWhen the internal array runs out of capacity, the list allocates a larger array and copies references to it. That resize is more expensive than an ordinary append, but it happens occasionally. Across many additions, appending to an ArrayList is amortized constant time: the average cost per addition stays close to constant. If you know an approximate size in advance, provide an initial capacity to reduce resizing:
List<Integer> marks = new ArrayList<>(500);Capacity is not the same as size. Size is the number of actual elements; capacity is reserved room. Avoid guessing a huge capacity merely for a small list because unused array space still consumes memory.
How LinkedList stores elements
A LinkedList stores every element in its own node. In Java, it is doubly linked: a node refers to the previous node and the next node. Adding a new node next to a known node only changes a few references. Removing a known node has the same local nature.
But a list index is not a node reference. To answer get(500), LinkedList starts at the nearer end and walks node by node until it reaches that position. The cost grows with the distance travelled. That makes indexed reads linear rather than constant time. In practice, separate node objects and pointer chasing can also use more memory and have poorer CPU cache locality than an array of references.
Operation costs: understand the conditions
Big-O notation describes growth, not a guarantee that one operation is always faster. The useful comparison is conditional:
- Read by index: ArrayList is O(1); LinkedList is O(n).
- Append: ArrayList is amortized O(1); LinkedList is O(1) when appending through its end reference.
- Insert at index: ArrayList must shift later references, so it is O(n). LinkedList must first walk to the index, also O(n).
- Remove by index: ArrayList shifts later references; LinkedList must walk to the node. Both are often O(n) from an indexed API.
- Insert using an existing ListIterator: LinkedList can link a node in O(1), while ArrayList still shifts later values.
The last case explains why “LinkedList is fast for insertion” is not wrong, merely too broad. It is fast when you already have the location as a node or iterator position. If your program first calls get(i) or searches through the list to discover that position, the traversal may dominate the cost.
A common performance trap: indexed looping over LinkedList
This loop is reasonable for an ArrayList but costly for a LinkedList:
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}Each get(i) can traverse part of the linked chain. Repeating it for every index can turn one full traversal into roughly quadratic work. When you only need each value in order, use an enhanced for loop or an iterator. Both list types can then be traversed linearly:
for (String module : list) {
System.out.println(module);
}This is a good reminder that the algorithm often matters more than the collection class. An inefficient access pattern cannot be fixed simply by swapping one List implementation for another.
Insertions near the beginning
Adding at index zero to an ArrayList moves every existing reference one position to the right. If you repeatedly prepend values, that repeated shifting can be expensive. LinkedList can add at the front directly because it keeps a reference to its first node. Yet a stack or queue requirement is usually clearer with Deque, not with List methods.
Deque<String> recentPages = new ArrayDeque<>();
recentPages.addFirst("Home");
recentPages.addFirst("Courses");
String current = recentPages.removeFirst();ArrayDeque is commonly preferred for stack and queue behaviour. It avoids LinkedList node allocation, does not permit null elements, and has methods that state intent: addFirst, addLast, removeFirst, and removeLast. Use LinkedList as a deque only when a specific API or integration makes it appropriate.
Memory and locality
ArrayList stores references together in one array, which is compact and friendly to modern CPU caches during sequential iteration. LinkedList needs a node object for every element plus previous and next references. That extra structure can increase memory use and create more allocation work. For a very large list, these practical costs may matter even when the theoretical operation count appears similar.
This does not mean ArrayList is always smaller in every situation. It means memory behaviour is part of the trade-off. Profile realistic data and workloads rather than relying on an isolated microbenchmark. A benchmark that creates lists once and runs on a warm JVM may not represent a web request, a database import, or a user-facing application.
Removing items safely while iterating
Do not remove directly from a list inside an enhanced for loop. Most standard list iterators are fail-fast: structural modification outside the iterator is detected and can throw ConcurrentModificationException. Use an iterator’s own remove() method when removal depends on the current element:
Iterator<String> iterator = modules.iterator();
while (iterator.hasNext()) {
String module = iterator.next();
if (module.isBlank()) {
iterator.remove();
}
}For simple filtering, removeIf(String::isBlank) can be clearer. The right approach depends on the Java version and whether you need additional work during traversal. The important point is that mutation and iteration must use a safe, deliberate mechanism.
ListIterator and editing a known position
When an editor, parser, or algorithm is already walking a list, ListIterator can add or remove values at its current position. LinkedList benefits most because it can adjust nearby links without shifting an array. Consider a token-processing task that inserts a marker immediately after a matched token:
ListIterator<String> iterator = tokens.listIterator();
while (iterator.hasNext()) {
if ("BEGIN".equals(iterator.next())) {
iterator.add("MARKER");
}
}This is a valid LinkedList use case when the program naturally has the iterator position. It is still worth considering whether a different representation, such as a StringBuilder, array, tree, or domain-specific structure, models the task better. Do not introduce LinkedList only because an algorithm performs a few insertions.
Thread safety is a separate concern
Neither ArrayList nor LinkedList is inherently thread-safe. Choosing LinkedList does not make concurrent changes safe. If multiple threads modify a collection, protect access with appropriate synchronization or choose a concurrent collection designed for the access pattern. A CopyOnWriteArrayList can help when reads are extremely frequent and changes are rare; a blocking queue can fit producer-consumer work. These have very different trade-offs from ordinary lists.
Also remember that synchronizing a list does not automatically make the objects inside it immutable or thread-safe. Define ownership and mutation rules at the application level.
Measure a real workload before changing collections
If performance genuinely matters, create a small benchmark that resembles the work your program performs. Include realistic list sizes, the ratio of reads to writes, and the location of inserts or removals. Warm-up matters on the JVM because just-in-time compilation can make an early timing misleading. For serious measurements, use the Java Microbenchmark Harness (JMH) instead of printing elapsed time around one loop.
For example, a benchmark that only appends one million values may suggest that both implementations are acceptable, while a web feature might actually read random indexes thousands of times after loading the values. Conversely, a parser that repeatedly edits at a cursor has a different shape from either case. Record the behaviour first, choose the clearest suitable structure, then measure before and after a targeted change. A 10% improvement in an operation that uses 1% of request time is rarely worth a less maintainable design.
Example: choose the collection from the feature
Imagine three features in a student portal. A course page loads lesson cards, displays them in sequence, and occasionally reads a card by position. That is an ArrayList-shaped feature. A browser-history control needs to add and remove pages at either end; an ArrayDeque expresses it better. A specialised text or token editor that walks a cursor through a sequence and makes many edits exactly at that cursor may be a LinkedList candidate, provided profiling confirms the need.
Notice that none of these choices depend on the raw number of elements alone. A small list can still suffer from an awkward access pattern, and a large ArrayList can work very well when the application appends values and scans them. Match the collection to operations, not to a vague idea of “large data.”
Common mistakes to avoid
- Choosing LinkedList because insertions sound frequent. Check whether you know the insertion point without an index search.
- Using LinkedList for a queue by default. Prefer ArrayDeque for normal stack and queue operations.
- Looping with get(i) over any list interface. Use iteration when indexed access is not required.
- Exposing a concrete collection in an API. Return or accept List when callers only need list behaviour.
- Optimising before measuring. Start with readable code and profile representative workloads.
A practical selection checklist
- Do callers need frequent random reads? Start with ArrayList.
- Are values mostly appended then iterated? Start with ArrayList.
- Is the real task first-in-first-out or last-in-first-out? Use ArrayDeque.
- Does the algorithm already hold a ListIterator and edit nearby nodes repeatedly? Evaluate LinkedList.
- Could a map, set, queue, or domain-specific object express the problem more accurately than a list?
For Java learners, the best exercise is to implement the same small feature with an ArrayList and an ArrayDeque, then explain why each operation fits or does not fit. This builds better collection instincts than memorising a table alone. For structured practice with collections and data structures, see Jaipur Engineers’ Core Java course details and the IT course catalog.
For API details, read Oracle’s ArrayList documentation, LinkedList documentation, and ArrayDeque documentation.
Frequently Asked Questions
Which is faster, ArrayList or LinkedList?
ArrayList is usually faster for indexed reads, appends, and ordinary iteration. LinkedList can be useful for local edits at an already-known iterator position, but the right choice depends on the actual access pattern.
Should I use LinkedList as a queue in Java?
Usually choose ArrayDeque for ordinary queue and stack operations. Its deque API expresses the intent and it commonly has lower overhead than a node-based LinkedList.
Can I remove items while looping through an ArrayList?
Yes, but use an Iterator and its remove method, or a suitable method such as removeIf. Do not structurally modify the list directly inside an enhanced for loop.
Want a structured Java learning path?
Explore Jaipur Engineers course options to connect Java fundamentals, debugging, backend development and project practice in a guided learning plan.