Collections Framework · Lesson 31 of 42
Lists: ArrayList and LinkedList
Arrays have a fixed size. Real data doesn't: a cart gains and loses items, a feed grows as you scroll. The Java Collections Framework provides ready-made, well-tested data structures, and the most used of all is ArrayList. Collections are also the single biggest topic in Java interviews.
In this lesson
- The Collections Framework at a glance
ArrayListmethods and how it growsLinkedListand when (rarely) to prefer it- Removing safely while iterating, and immutable lists
The framework at a glance
Core interfaces and their main implementations
Collection / Map
- Listordered, duplicates allowed – ArrayList, LinkedList
- Setno duplicates – HashSet, LinkedHashSet, TreeSet
- Queue / Dequeprocessing order – ArrayDeque, PriorityQueue
- Mapkey → value – HashMap, LinkedHashMap, TreeMap
Declare variables with the interface type (List, Set, Map) and create them with an implementation – you can swap implementations later without touching the rest of the code.
ArrayList
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> cart = new ArrayList<>();
cart.add("rice");
cart.add("dal");
cart.add(0, "oil"); // insert at a position
cart.addAll(List.of("salt", "sugar"));
System.out.println(cart + " size " + cart.size());
System.out.println(cart.get(1) + " " + cart.indexOf("salt") + " " + cart.contains("tea"));
cart.set(1, "basmati rice"); // replace
cart.remove("salt"); // by value
cart.remove(0); // by index
System.out.println(cart);
for (String item : cart) System.out.print(item.toUpperCase() + " ");
System.out.println();
cart.clear();
System.out.println(cart.isEmpty());
}
}
[oil, rice, dal, salt, sugar] size 5 rice 3 false [basmati rice, dal, sugar] BASMATI RICE DAL SUGAR true
How ArrayList works inside
An ArrayList is a resizable array
- Backing arraystarts with room for 10 elements
- add() when fullcreates a new array about 1.5× bigger
- Copies the elementsthen adds the new one
- get(i) is instantdirect index into the array
Common mistake: remove(int) vs remove(Object) with Integer lists
For a List<Integer>, list.remove(1) removes the element at index 1, not the value 1. To remove the value, write list.remove(Integer.valueOf(1)).
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>(List.of(5, 1, 7, 1));
nums.remove(1); // removes the element at INDEX 1
System.out.println(nums);
nums.remove(Integer.valueOf(1)); // the value 1
System.out.println(nums);
}
}
[5, 7, 1] [5, 7]
LinkedList
A LinkedList stores each element in a node that points to the previous and next nodes. Adding or removing at the ends is cheap, but reaching index i means walking from one end.
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> history = new LinkedList<>();
history.addLast("home");
history.addLast("courses");
history.addLast("java");
history.addFirst("login");
System.out.println(history);
System.out.println(history.getFirst() + " … " + history.getLast());
history.removeLast(); // "back" button
System.out.println(history);
}
}
[login, home, courses, java] login … java [login, home, courses]
| Operation | ArrayList | LinkedList |
|---|---|---|
get(i) | O(1) – instant | O(n) – walks the nodes |
| add at the end | O(1) amortised | O(1) |
| add/remove at the start | O(n) – shifts elements | O(1) |
| Memory | compact | extra node objects with two pointers each |
Interview angle
In practice ArrayList wins almost every time, because CPUs love contiguous memory. If you need a queue or stack with fast operations at both ends, use ArrayDeque, not LinkedList.
Removing while iterating
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> marks = new ArrayList<>(List.of(78, 32, 91, 25, 66));
try {
for (Integer m : marks) if (m < 40) marks.remove(m); // modifies during for-each
} catch (java.util.ConcurrentModificationException e) {
System.out.println("ConcurrentModificationException!");
}
marks = new ArrayList<>(List.of(78, 32, 91, 25, 66));
Iterator<Integer> it = marks.iterator();
while (it.hasNext()) if (it.next() < 40) it.remove(); // safe
System.out.println(marks);
List<Integer> more = new ArrayList<>(List.of(10, 50, 20));
more.removeIf(m -> m < 40); // simplest
System.out.println(more);
}
}
ConcurrentModificationException! [78, 91, 66] [50]
Immutable lists
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> days = List.of("Mon", "Tue", "Wed"); // unmodifiable
try {
days.add("Thu");
} catch (UnsupportedOperationException e) {
System.out.println("List.of is read-only");
}
List<String> editable = new ArrayList<>(days); // copy when you need changes
editable.add("Thu");
System.out.println(editable);
}
}
List.of is read-only [Mon, Tue, Wed, Thu]
Practice
Try it yourself
Remove duplicates from [3, 1, 3, 2, 1, 5] while keeping the original order.
Show solution
import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List<Integer> nums = List.of(3, 1, 3, 2, 1, 5); List<Integer> unique = new ArrayList<>(); for (int n : nums) if (!unique.contains(n)) unique.add(n); System.out.println(unique); } }[3, 1, 2, 5]
Quick check
Which is faster for get(5000): ArrayList or LinkedList?
ArrayList – O(1) direct access versus O(n) traversal.
How do you remove items safely while iterating?
Use Iterator.remove() or list.removeIf(...), not list.remove() inside a for-each.
Can you add to a list created with List.of?
No – it throws UnsupportedOperationException.
Summary
- Declare
List, createArrayList; it is a resizable array with O(1) access. - LinkedList is rarely the better choice; use ArrayDeque for queues and stacks.
- Remove with Iterator or removeIf;
List.ofis immutable.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.