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

Updated 14 Nov 20265 min read
ArrayList and LinkedList in Java: Runnable Examples, Costs and Common Errors

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:

java
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:

java
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:

Code
[80, 90, 91]
90
3

add(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

java
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].

Code
[Noida, Delhi, Mathura, Agra]
removed=Jaipur
first=Noida, last=Agra

Endpoint 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().

Compare operation costs without memorising a slogan

Operation

ArrayList

LinkedList

Important condition

get/set by index

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

contains/indexOf

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.

Two workload cards: 8,000 indexed reads pointing to ArrayList, and 5,000 addLast plus removeFirst cycles pointing to LinkedList.

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.

  1. 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].

  2. Start with LinkedList<String> q = new LinkedList<>(List.of("A", "B"));, run q.addFirst("X") and String y = q.removeLast(). The answers are q = [X, A] and y = "B".

  3. Choose between the two lists for 50,000 indexed reads, 5 tail appends and no endpoint removals. Choose ArrayList because 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.