</>

Technology

Core Java

Difficulty

Intermediate

Interview Question

What is the difference between ArrayList and LinkedList in Java?

Answer

ArrayList vs LinkedList

Both implement the List interface but have different internal structures and performance characteristics.

Internal Structure

ArrayList — backed by a dynamic array:

CODE
Index:  [0]      [1]      [2]      [3]
Data:  "Alice" "Bob"  "Charlie" "Dave"
       ↑ contiguous memory — O(1) access by index

LinkedList — backed by a doubly-linked list:

CODE
null ← [Alice|→] ↔ [Bob|→] ↔ [Charlie|→] ↔ [Dave|→] → null
       Each node has: data + prev pointer + next pointer

Performance Comparison

OperationArrayListLinkedListWhy
get(i)O(1) ✅ fastO(n) ❌ slowArray index vs traverse list
add at endO(1) amortizedO(1)Append to array / tail pointer
add at indexO(n) ❌ slowO(n) ❌ slowShift elements / traverse then add
remove at indexO(n) ❌ slowO(n)*Shift elements / pointer update
MemoryLess (array)More (pointers)No pointers vs prev+next pointers
Iterator add/removeO(n)O(1) ✅With ListIterator

Code Examples

Java
// ArrayList — use when you read frequently by index
List<String> arrayList = new ArrayList<>();
arrayList.add("Alice");
arrayList.add("Bob");
arrayList.add("Charlie");

String name = arrayList.get(1);  // O(1) — instant
System.out.println(name);        // "Bob"

// LinkedList — use when you insert/delete frequently
LinkedList<String> linkedList = new LinkedList<>();
linkedList.add("Alice");
linkedList.addFirst("Zero");    // O(1) — add to front
linkedList.addLast("Dave");     // O(1) — add to back
linkedList.removeFirst();       // O(1) — remove front
linkedList.pollLast();          // O(1) — remove & return last

// LinkedList also implements Deque (double-ended queue)
Deque<String> deque = new LinkedList<>();
deque.push("item1");  // push to front
deque.pop();          // remove from front

When to Use

ScenarioChoose
Frequent random access by indexArrayList
Frequent search/iterationArrayList
Frequent insert/delete at beginningLinkedList
Need to use as Queue or DequeLinkedList
Memory is criticalArrayList
Default choiceArrayList (most common)

In Automation Testing

Java
// ArrayList — storing and accessing test results by index
List<String> testResults = new ArrayList<>();
testResults.add("PASS");
testResults.add("FAIL");
testResults.add("SKIP");
System.out.println(testResults.get(0)); // "PASS"

// LinkedList — processing test steps as queue (FIFO)
Queue<String> testSteps = new LinkedList<>();
testSteps.offer("Open Browser");
testSteps.offer("Navigate to URL");
testSteps.offer("Login");
testSteps.offer("Verify Dashboard");

while (!testSteps.isEmpty()) {
    System.out.println("Executing: " + testSteps.poll());
}

Follow AutomateQA

Related Topics