ArrayList and LinkedList
ArrayList and LinkedList in Java
Java's Collections Framework provides generic, resizable data structures.
List interface
Both ArrayList and LinkedList implement java.util.List. Program to the interface:
List<String> names = new ArrayList<>();ArrayList Backed by a dynamic array. Provides O(1) random access by index. Adding at the end is amortised O(1). Insertions/deletions in the middle are O(n).
LinkedList
Doubly-linked list. O(1) insertions/deletions at the ends. O(n) random access. Also implements Deque.
Common List operations
add(element),add(index, element)get(index),set(index, element)remove(index),remove(Object)size(),isEmpty(),contains(element)Collections.sort(list),list.sort(Comparator)
Key points:
- Use
ArrayListfor most use cases — it has better cache locality. - Use
LinkedListwhen frequent insertions/deletions at both ends are needed. - Generic type parameters prevent
ClassCastExceptionat runtime.
Code Examples
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ListDemo {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
fruits.add("Banana");
fruits.add("Apple");
fruits.add("Cherry");
fruits.add(1, "Mango"); // insert at index 1
System.out.println("Size: " + fruits.size());
System.out.println("Index 0: " + fruits.get(0));
Collections.sort(fruits);
System.out.println("Sorted: " + fruits);
fruits.remove("Mango");
System.out.println("After remove: " + fruits);
}
}ArrayList grows automatically as you add elements. Collections.sort() sorts in natural order (alphabetical for Strings).
import java.util.List;
public class IterationDemo {
public static void main(String[] args) {
List<Integer> numbers = new java.util.ArrayList<>(List.of(3, 1, 4, 1, 5, 9, 2, 6));
// for-each
int sum = 0;
for (int n : numbers) sum += n;
System.out.println("Sum: " + sum);
// removeIf
numbers.removeIf(n -> n < 3);
System.out.println("After removeIf < 3: " + numbers);
// replaceAll
numbers.replaceAll(n -> n * 2);
System.out.println("After *2: " + numbers);
}
}removeIf and replaceAll accept lambdas, making bulk operations concise. List.of() creates an immutable list used here as a source.
Quick Quiz
1. Which List implementation provides O(1) random access by index?
2. What does programming to the List interface mean?
Was this lesson helpful?