ArrayList and LinkedList in Java: Runnable Examples, Costs and Common Errors
Build a reliable mental model for Java lists, run two complete programs, compare operation costs, and avoid overload, bounds and traversal traps.
KnowledgeGate Team
Exam prep & CS education

You know arrays and basic loops, but Java's ArrayList and LinkedList can still look interchangeable. Then one indexed operation feels unexpectedly slow, or remove(1) deletes the wrong integer. ArrayList and LinkedList differ in internal representation, operation costs, workload fit, and mutation behavior. Implementation and complexity statements are attributed to Oracle's Java SE 21 ArrayList API documentation and its LinkedList contract.
Start with List, then choose an implementation
List<E> is an ordered, index-based interface. ArrayList<E> and LinkedList<E> are implementations with different internal representations:
List<Integer> scores = new ArrayList<>();
List<String> stops = new LinkedList<>();Programming to List keeps common list operations swappable. Use a LinkedList variable when you deliberately need deque methods such as addFirst, addLast, peekFirst and removeLast.
Oracle describes ArrayList as a resizable-array implementation. LinkedList is a doubly-linked implementation of both List and Deque. A logical index means the position Java exposes, not a numbered slot stored inside every linked node. Generics require reference types, so use Integer, not int. The beginner imports are import java.util.ArrayList;, import java.util.LinkedList; and import java.util.List;. Review value equality before studying remove(Object).
Build and update an ArrayList with exact output
This complete program inserts, replaces and removes values:
import java.util.ArrayList;
import java.util.List;
public class ArrayListDemo {
public static void main(String[] args) {
List<Integer> scores = new ArrayList<>();
scores.add(72);
scores.add(88);
scores.add(91);
scores.add(1, 80);
scores.set(2, 90);
scores.remove(Integer.valueOf(72));
System.out.println(scores);
System.out.println(scores.get(1));
System.out.println(scores.size());
}
}Trace it after every mutation:
[] -> [72] -> [72, 88] -> [72, 88, 91] -> [72, 80, 88, 91] -> [72, 80, 90, 91] -> [80, 90, 91]
The output is:
[80, 90, 91]
90
3add(1, 80) inserts and shifts later logical elements. set(2, 90) replaces a value without changing the size. remove(Integer.valueOf(72)) chooses the value overload.
Oracle specifies constant time for size, isEmpty, get, set, iterator and list-iterator operations. Appending is amortised O(1), while other operations are roughly linear. Amortised means occasional resize work is spread across many appends.
Use LinkedList as a list and as a deque
import java.util.LinkedList;
public class LinkedListDemo {
public static void main(String[] args) {
LinkedList<String> stops = new LinkedList<>();
stops.addLast("Delhi");
stops.addLast("Agra");
stops.addLast("Jaipur");
stops.addFirst("Noida");
stops.add(2, "Mathura");
String removed = stops.removeLast();
System.out.println(stops);
System.out.println("removed=" + removed);
System.out.println("first=" + stops.peekFirst() + ", last=" + stops.peekLast());
}
}The states are [] -> [Delhi] -> [Delhi, Agra] -> [Delhi, Agra, Jaipur] -> [Noida, Delhi, Agra, Jaipur] -> [Noida, Delhi, Mathura, Agra, Jaipur] -> [Noida, Delhi, Mathura, Agra].
[Noida, Delhi, Mathura, Agra]
removed=Jaipur
first=Noida, last=AgraEndpoint additions and removals relink nodes directly. However, add(2, "Mathura") first traverses to the indexed position. Oracle says indexed operations traverse from the nearer end. A linked insertion is O(1) only when the endpoint or insertion position is already available.
![ArrayList [72, 88, 91] shifting elements after add(1, 80), and a LinkedList chain Noida to Agra with Jaipur detached by removeLast().](https://cdn.knowledgegate.ai/blog-assets/blog_asset_1784568725977_eyt875.jpg)
Compare operation costs without memorising a slogan
Operation | ArrayList | LinkedList | Important condition |
|---|---|---|---|
| O(1) | O(n) | LinkedList must traverse |
Append at the end | Amortised O(1) | O(1) | ArrayList may occasionally resize |
Add/remove at the front | O(n) | O(1) | Use LinkedList endpoint methods |
Add/remove at an arbitrary index | O(n) | O(n) | ArrayList shifts; LinkedList first traverses |
| O(n) | O(n) | Both may inspect every value |
When the workload is unknown, begin with ArrayList. Indexed reads and compact traversal are common. Choose LinkedList when the actual access pattern benefits, such as repeated endpoint deque operations or repeated edits through an iterator that is already positioned.
LinkedList nodes carry links and separate allocations, but exact memory use and speed depend on the JVM and data. Big-O is not a benchmark. For a pure stack or queue requirement, compare ArrayDeque too.
Fully worked choice: match the list to the workload
Workload A: Start with 5,000 student records, perform exactly 8,000 indexed reads, append 200 records, and remove only 3 records from the front. Choose ArrayList. The 8,000 O(1) indexed reads dominate, while three front shifts are rare. This is asymptotic reasoning, not a claim about measured milliseconds.
Workload B: Start with job IDs [104, 107, 112]. Perform 5,000 cycles containing one addLast(nextId) and one removeFirst(), with no indexed reads. That is 5,000 additions + 5,000 removals = 10,000 endpoint operations. If the choice is restricted to these lists, choose LinkedList: both required endpoint operations are O(1), while each ArrayList front removal shifts later logical elements. In production, benchmark ArrayDeque for this pure queue case too.

Common errors, exact failures and safe fixes
Overload trap: Given List<Integer> values = new ArrayList<>(List.of(10, 20, 30));, values.remove(1) calls remove(int index), deletes the element at index 1 and leaves [10, 30]. Starting again from the original list, values.remove(Integer.valueOf(20)) calls remove(Object) and also leaves [10, 30].
Bounds trap: For [80, 90, 91], valid get, set and remove indices are 0, 1 and 2. add(3, 95) is allowed because insertion may happen at size(). get(3) throws IndexOutOfBoundsException.
Mutation trap: Do not remove directly from a list inside an enhanced for loop. For mutable input [3, 6, 9, 10], use values.removeIf(n -> n % 3 == 0). It removes 3, 6 and 9, producing [10]. For cursor state, safe Iterator.remove(), and comparator chains, use Java Iterators and Comparators; this section only explains list mutation and implementation cost.
Performance trap: for (int i = 0; i < linked.size(); i++) linked.get(i); can be quadratic because each indexed access may traverse nodes. Use an enhanced for loop or iterator for one linear traversal. Also remember that List.of(10, 20, 30) is unmodifiable. Copy it into new ArrayList<>(...) or new LinkedList<>(...) before mutation.
Exam and interview questions on list operations
Common questions ask you to trace overloaded remove, select an implementation from an operation mix, compare indexed access with endpoint operations, or repair unsafe mutation. Use four steps: mark declared and runtime types, write the list after every mutation, resolve overloads before evaluating values, then count traversals or shifts.
Run
List<Integer> x = new ArrayList<>(List.of(4, 7, 4)); x.remove(Integer.valueOf(4)); x.add(1, 9);. Removal gives[7, 4]; insertion gives[7, 9, 4].Start with
LinkedList<String> q = new LinkedList<>(List.of("A", "B"));, runq.addFirst("X")andString y = q.removeLast(). The answers areq = [X, A]andy = "B".Choose between the two lists for 50,000 indexed reads, 5 tail appends and no endpoint removals. Choose
ArrayListbecause indexed reads dominate.
For the wider List, Set, Queue and Map decision map, use the Collections Framework in Java overview; this tutorial stays with ArrayList versus LinkedList representation, costs and mutation traps.
The short version and the next step
Use ArrayList as the normal general-purpose list, especially for indexed reading and iteration. Use LinkedList when repeated endpoint operations or edits through an already-positioned iterator match the workload. Do not assume linked always means faster insertion. Both preserve order and allow duplicates.
Follow the language sequence in the Java Programming course, move from collections to problem solving with DSA Using Java, or browse the Coding & Skills category. Run both examples, complete the three exercises without an IDE, then verify the outputs in Java.
Keep learning
Map, Set and WeakMap in JavaScript: Runnable Examples and Common Errors
Choose the right JavaScript collection by tracing a stock Map, deduplicating IDs with Set, and attaching object-owned metadata with WeakMap. Includes output traps and self-checking exercises.
Java Iterators and Comparators: Runnable Examples, Sorting Rules and Common Traps
Learn when to use Iterator, Comparable and Comparator through one Java 17 Student example, exact outputs, cursor traces and safe sorting rules.
INNER JOIN in SQL: Syntax, Worked Examples, and Common Errors
Build INNER JOIN intuition with a customer-order dataset. Trace exact row matches, handle one-to-many results, extend to payments, and practise common interview patterns.
Enums and Typedef in C: Syntax, Worked Examples, and Common Errors
Learn how C enums name integer states and typedef aliases existing types. Trace two complete programs, then avoid collisions, hidden pointers, invalid values, and size assumptions.





