Introduction & Syntax
Collections Framework · Study material
The Java Collections Framework is the standard library of data structures in java.util: resizable lists, sets without duplicates, queues, stacks, priority queues and maps, all behind a small set of interfaces. Instead of managing arrays and their sizes by hand, you pick the right interface – List, Set, Queue, Deque – and a suitable implementation such as ArrayList, HashSet, TreeSet, ArrayDeque or PriorityQueue. Every real Java application uses collections, and choosing the right one (and knowing its cost) is a core interview skill. This page covers the hierarchy, each family with runnable examples, iterators and the infamous ConcurrentModificationException, the Collections utility class, immutable collections and the Arrays.asList trap, and a guide to choosing. Maps are covered in the next topic. Then practise with 60 questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – compiled and run on Java 21.
On this page
- The Collection hierarchy and generics
- List: ArrayList and LinkedList
- Set: HashSet, LinkedHashSet and TreeSet
- Queue, Deque and PriorityQueue
- Iterators, ListIterator and ConcurrentModificationException
- Collections utilities, immutable collections and choosing the right type
The hierarchy
| Interface | Meaning | Main implementations |
|---|---|---|
Collection<E> | a group of elements (add, remove, contains, size, iterate) | – |
List<E> | ordered, indexed, duplicates allowed | ArrayList, LinkedList |
Set<E> | no duplicates | HashSet, LinkedHashSet, TreeSet (SortedSet / NavigableSet) |
Queue<E> | elements waiting to be processed | ArrayDeque, PriorityQueue, LinkedList |
Deque<E> | double-ended queue; also a stack | ArrayDeque, LinkedList |
Map<K,V> | key → value pairs (not a Collection) | HashMap, LinkedHashMap, TreeMap |
Collections are generic: List<String> holds only Strings, checked at compile time. Declare variables with the interface (List<String> names = new ArrayList<>()) so the implementation can change later.
List
ArrayList stores elements in a resizable array: fast random access and fast appends. LinkedList is a doubly linked list: cheap insertion at the ends but slow indexed access. In practice ArrayList (or ArrayDeque for queues) is almost always the better choice.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> cities = new ArrayList<>(); // declare with the interface, create the implementation
cities.add("Pune");
cities.add("Delhi");
cities.add("Chennai");
cities.add(1, "Mumbai"); // insert at index 1
cities.add("Delhi"); // lists allow duplicates and keep order
System.out.println(cities + " size " + cities.size());
System.out.println(cities.get(2) + " " + cities.indexOf("Delhi") + " " + cities.lastIndexOf("Delhi") + " " + cities.contains("Goa"));
cities.set(0, "Pune City"); // replace
cities.remove("Delhi"); // removes the FIRST match
cities.remove(0); // removes by index
System.out.println(cities + " " + cities.subList(0, 2) + " " + cities.isEmpty());
}
}
[Pune, Mumbai, Delhi, Chennai, Delhi] size 5 Delhi 2 4 false [Mumbai, Chennai, Delhi] [Mumbai, Chennai] false
Set
Sets reject duplicates using equals and hashCode (or compareTo for TreeSet). HashSet is fastest with no order guarantee, LinkedHashSet keeps insertion order, and TreeSet keeps elements sorted and offers navigation methods such as first, ceiling and headSet.
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
List<String> visits = List.of("Goa", "Agra", "Pune", "Goa", "Delhi", "Agra");
Set<String> hash = new HashSet<>(visits); // no duplicates, no guaranteed order, fastest
Set<String> linked = new LinkedHashSet<>(visits); // no duplicates, insertion order
Set<String> tree = new TreeSet<>(visits); // no duplicates, sorted order
System.out.println(hash.size() + " " + hash.contains("Pune"));
System.out.println(linked);
System.out.println(tree);
TreeSet<Integer> scores = new TreeSet<>(List.of(72, 95, 40, 88, 61));
System.out.println(scores.first() + " " + scores.last() + " " + scores.ceiling(80) + " " + scores.floor(80) + " " + scores.headSet(70) + " " + scores.descendingSet());
System.out.println(linked.add("Goa") + " " + linked.add("Ooty")); // add returns false for a duplicate
}
}
4 true [Goa, Agra, Pune, Delhi] [Agra, Delhi, Goa, Pune] 40 95 88 72 [40, 61] [95, 88, 72, 61, 40] false true
Queue, Deque and PriorityQueue
A queue processes elements first-in-first-out with offer, poll and peek (which return null instead of throwing). ArrayDeque is also the recommended stack (push, pop). A PriorityQueue always returns the smallest element (or the highest priority by a Comparator) – note that its toString order is not sorted.
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.PriorityQueue;
import java.util.Queue;
public class Main {
public static void main(String[] args) {
Queue<String> line = new ArrayDeque<>(); // FIFO queue
line.offer("Asha"); line.offer("Ravi"); line.offer("Meena");
System.out.println(line.poll() + " served, next " + line.peek() + ", waiting " + line);
Deque<Integer> stack = new ArrayDeque<>(); // LIFO stack (prefer it over java.util.Stack)
stack.push(1); stack.push(2); stack.push(3);
System.out.println(stack.pop() + " " + stack.peek() + " " + stack);
Deque<String> both = new ArrayDeque<>(); // double-ended
both.offerFirst("B"); both.offerLast("C"); both.offerFirst("A");
System.out.println(both + " " + both.pollLast() + " " + both);
PriorityQueue<Integer> pq = new PriorityQueue<>(); // always gives the SMALLEST first
for (int n : new int[]{40, 10, 30, 20, 50}) pq.offer(n);
StringBuilder sb = new StringBuilder();
while (!pq.isEmpty()) sb.append(pq.poll()).append(' ');
System.out.println(sb.toString().trim());
}
}
Asha served, next Ravi, waiting [Ravi, Meena] 3 2 [2, 1] [A, B, C] C [A, B] 10 20 30 40 50
Iterators and ConcurrentModificationException
Changing a collection's structure while looping over it with for-each throws ConcurrentModificationException (the iterator is "fail-fast"). Remove elements through Iterator.remove() or, more simply, with removeIf.
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>(List.of(5, 12, 7, 20, 3, 18));
try {
for (Integer n : nums) if (n > 10) nums.remove(n); // ✘ modifying while iterating
} catch (ConcurrentModificationException e) {
System.out.println("ConcurrentModificationException");
}
List<Integer> a = new ArrayList<>(List.of(5, 12, 7, 20, 3, 18));
Iterator<Integer> it = a.iterator(); // ✔ remove through the iterator
while (it.hasNext()) if (it.next() > 10) it.remove();
System.out.println(a);
List<Integer> b = new ArrayList<>(List.of(5, 12, 7, 20, 3, 18));
b.removeIf(n -> n > 10); // ✔ simplest (Java 8+)
System.out.println(b);
}
}
ConcurrentModificationException [5, 7, 3] [5, 7, 3]
The Collections utility class
java.util.Collections provides static algorithms: sort, reverse, shuffle, swap, rotate, max, min, frequency, binarySearch, and factories for empty, singleton, synchronized and unmodifiable collections.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> marks = new ArrayList<>(List.of(67, 92, 45, 88, 92, 73));
Collections.sort(marks);
System.out.println(marks + " max " + Collections.max(marks) + " min " + Collections.min(marks) + " freq(92) " + Collections.frequency(marks, 92));
System.out.println("index of 88: " + Collections.binarySearch(marks, 88)); // list must be sorted
Collections.reverse(marks);
System.out.println(marks);
Collections.swap(marks, 0, marks.size() - 1);
Collections.rotate(marks, 2);
System.out.println(marks);
List<String> names = new ArrayList<>(List.of("Ravi", "asha", "Meena", "zoya"));
names.sort(String.CASE_INSENSITIVE_ORDER);
System.out.println(names + " " + Collections.nCopies(3, "ab") + " " + Collections.emptyList());
names.sort(Comparator.comparing(String::length).thenComparing(Comparator.reverseOrder()));
System.out.println(names);
}
}
[45, 67, 73, 88, 92, 92] max 92 min 45 freq(92) 2 index of 88: 3 [92, 92, 88, 73, 67, 45] [67, 92, 45, 92, 88, 73] [asha, Meena, Ravi, zoya] [ab, ab, ab] [] [zoya, asha, Ravi, Meena]
Immutable and unmodifiable collections
List.of, Set.of and Map.of (Java 9) create truly immutable collections that reject nulls. Collections.unmodifiableList is only a read-only view – changes to the underlying list still show through – and List.copyOf takes an immutable snapshot. Arrays.asList returns a fixed-size list backed by the array: set works but add and remove do not.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Main {
static String tryAdd(List<String> l) {
try { l.add("x"); return "added"; } catch (UnsupportedOperationException e) { return "UOE"; }
}
static String trySet(List<String> l) {
try { l.set(0, "x"); return "set"; } catch (UnsupportedOperationException e) { return "UOE"; }
}
public static void main(String[] args) {
List<String> source = new ArrayList<>(List.of("a", "b"));
List<String> of = List.of("a", "b"); // fully immutable, no nulls
List<String> asList = Arrays.asList("a", "b"); // fixed size, but set() works
List<String> view = Collections.unmodifiableList(source); // read-only VIEW of source
List<String> copy = List.copyOf(source); // immutable snapshot
System.out.println(tryAdd(of) + " " + trySet(of));
System.out.println(tryAdd(asList) + " " + trySet(asList) + " " + asList);
source.add("c");
System.out.println(tryAdd(view) + " " + view + " " + copy);
}
}
UOE UOE UOE set [x, b] UOE [a, b, c] [a, b]
Common mistakes
- Removing elements inside a for-each loop.
- Using a custom class in a HashSet without equals and hashCode.
- Calling list.remove(1) on a List<Integer> expecting to remove the value 1.
- Adding to List.of or Arrays.asList results.
- Expecting HashSet to keep insertion order or PriorityQueue's toString to be sorted.
- Using LinkedList for random access or java.util.Stack/Vector in new code.
- Binary-searching an unsorted list.
- Declaring variables as ArrayList instead of List.
Key points to remember
- List = ordered with duplicates; Set = unique; Queue/Deque = processing order.
- Default choices: ArrayList, HashSet, ArrayDeque, HashMap.
- TreeSet and PriorityQueue need Comparable elements or a Comparator.
- Remove while iterating with Iterator.remove or removeIf.
- List.of is immutable; Arrays.asList is fixed-size; unmodifiableList is a view.
- Program to interfaces; use generics everywhere.
Frequently asked questions
ArrayList or LinkedList?
ArrayList in almost every case; it is faster even for many insertions because of memory locality. Use ArrayDeque if you need a queue.
Are collections thread-safe?
The basic ones are not. Use java.util.concurrent classes (covered in the concurrency topic) or Collections.synchronizedList for simple cases.
Can collections store primitives?
No – they store objects, so int values are autoboxed to Integer.
Where can I learn more?
Read Java Collections Framework and Java ArrayList, then practise with the exercises below.