SyntaxStudy
Sign Up
Java Beginner 1 min read

ArrayList and LinkedList

ArrayList and LinkedList are the two most commonly used List implementations in Java. ArrayList stores elements in a resizable array, making random access by index very fast (O(1)), while insertions and deletions in the middle of the list are slower because elements must be shifted. It is the default choice when you mostly read data or append to the end of the list. LinkedList uses a doubly-linked structure where each node holds a reference to the previous and next element. This makes insertions and deletions at arbitrary positions efficient (O(1) when you have the node reference), but random access is slow (O(n)) because you must traverse from the head. LinkedList also implements the Deque interface, so it can serve as a queue or a stack. Choosing between them depends on your usage pattern. Use ArrayList for frequent reads and rare structural changes. Use LinkedList when you frequently add or remove elements from the beginning or middle of the list, or when you need queue-like behaviour with addFirst/addLast/removeFirst/removeLast operations.
Example
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class ListDemo {
    public static void main(String[] args) {
        // --- ArrayList ---
        List<String> arrayList = new ArrayList<>();
        arrayList.add("Java");
        arrayList.add("Python");
        arrayList.add("Go");
        arrayList.add(1, "Kotlin"); // insert at index 1

        System.out.println("ArrayList: " + arrayList);
        System.out.println("Element at index 2: " + arrayList.get(2));

        arrayList.remove("Python");
        System.out.println("After remove: " + arrayList);

        // --- LinkedList ---
        LinkedList<String> linked = new LinkedList<>();
        linked.add("Alice");
        linked.add("Bob");
        linked.addFirst("Zara");   // O(1) prepend
        linked.addLast("Charlie"); // O(1) append

        System.out.println("\nLinkedList: " + linked);
        System.out.println("Peek first: " + linked.peekFirst());
        System.out.println("Poll last:  " + linked.pollLast()); // removes & returns

        // Iterating
        System.out.println("\nIterating LinkedList:");
        for (String name : linked) {
            System.out.println("  " + name);
        }
    }
}