Collection Framework Implementations
Java Collections Framework
A practical guide to collection interfaces, implementations and everyday development scenarios.
1. Architecture and Interfaces
The Java Collections Framework provides interfaces, implementations and utility methods for storing and processing groups of objects. Most are in java.util; concurrent implementations are in java.util.concurrent.
- Iterable supplies an iterator and enables the enhanced
forloop. Collection extends it and defines operations such asadd,remove,containsandsize. - List is an ordered, indexed sequence that permits duplicates. Its implementations include
ArrayList,LinkedListandVector. - Queue holds elements for processing; Deque supports both ends.
LinkedListimplements both List and Deque. - Set rejects duplicates.
SortedSetadds sorted order;NavigableSetadds navigation methods such asfloorandceiling.TreeSetimplements both. - Map stores key-value pairs. It is part of the framework but does not extend
Collection; its views, such askeySet(), are collections.
javac FileName.java and run with java ClassName.2. Choose the Right Collection
| Need | Typical choice | Important behavior |
|---|---|---|
| Indexed sequence, duplicates allowed | ArrayList | Insertion order; fast indexed access; middle inserts shift elements. |
| Items at both ends | ArrayDeque | Efficient queue or stack; no null elements. |
| FIFO work queue | ArrayDeque | Add at the tail and remove from the head. |
| Next item by priority | PriorityQueue | Head is the least element by natural order or comparator; iteration is not sorted. |
| Unique values | HashSet | No guaranteed iteration order; permits one null. |
| Unique values in insertion order | LinkedHashSet | Preserves insertion order; permits one null. |
| Unique values in sorted order | TreeSet | Uses natural order or a comparator to order and identify duplicates. |
| Find a value by key | HashMap | No guaranteed iteration order; permits one null key and null values. |
| Sorted keys or range queries | TreeMap | Keys are sorted; keys must be comparable by its ordering. |
Program to an interface when practical, for example List<String> names = new ArrayList<>();. Select the implementation according to ordering, operations, null handling and concurrency needs.
3. List: ArrayList, LinkedList and Vector
ArrayList uses a resizable array and is a good default for indexed access and appending. LinkedList is a doubly linked list: operations at its ends are efficient, but indexed access requires traversal. Vector is a legacy synchronized list; its individual methods are synchronized, not a complete solution for compound actions or iteration. Stack extends Vector; prefer Deque for a new stack.
Example: add, update, remove and copy
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
public class ListExample {
public static void main(String[] args) {
List<String> names = new ArrayList<>(Arrays.asList("Ana", "Ben", "Ana"));
names.add("Dev");
names.set(1, "Bea");
names.remove("Ana"); // removes the first matching value
System.out.println(names);
List<String> copy = new ArrayList<>(names);
List<String> destination = new ArrayList<>(Arrays.asList("-", "-", "-", "extra"));
Collections.copy(destination, copy);
System.out.println(destination);
List<String> linked = new LinkedList<>(copy);
List<String> legacy = new Vector<>(linked);
System.out.println(legacy);
}
}
Output:
[Bea, Ana, Dev]
[Bea, Ana, Dev, extra]
[Bea, Ana, Dev]
Collections.copy(destination, source) replaces existing positions; the destination must already have at least as many elements as the source, or it throws IndexOutOfBoundsException. A new ArrayList<>(source) makes a shallow copy and is usually simpler.Lists store references: a shallow copy has independent list structure but shares the contained objects. In List<Integer>, remove(1) removes index 1; use remove(Integer.valueOf(1)) to remove the value.
4. Queue, Deque and PriorityQueue
For an empty queue, poll() and peek() return null, while remove() and element() throw NoSuchElementException. For capacity-limited queues, offer() can return false when insertion fails; add() throws instead. Check the concrete implementation's contract.
ArrayDeque is a resizable-array implementation for FIFO queues and LIFO stacks. It does not accept null. LinkedList also implements Deque, but avoid null in queues because null is the empty-result sentinel. PriorityQueue removes the least element first by default, not necessarily the earliest inserted item.
Example: FIFO, stack and priority
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.PriorityQueue;
import java.util.Queue;
public class QueueExample {
public static void main(String[] args) {
Queue<String> tasks = new ArrayDeque<>();
tasks.offer("build");
tasks.offer("test");
System.out.println(tasks.poll());
System.out.println(tasks.peek());
Deque<String> history = new ArrayDeque<>();
history.push("first");
history.push("second");
System.out.println(history.pop());
Queue<Integer> priority = new PriorityQueue<>();
priority.offer(30);
priority.offer(10);
priority.offer(20);
while (!priority.isEmpty()) {
System.out.print(priority.poll() + " ");
}
System.out.println();
}
}
Output:
build
test
second
10 20 30
For a max-priority queue use new PriorityQueue<>(Collections.reverseOrder()). Iterating or printing a priority queue does not guarantee sorted order; poll elements to process them in priority order.
5. Set: HashSet, LinkedHashSet and TreeSet
Sets keep unique elements. HashSet does not guarantee iteration order, LinkedHashSet preserves insertion order, and TreeSet maintains sorted order. A TreeSet uses its comparator or natural ordering to decide whether two elements are duplicates.
Example: deduplication and sorted ranges
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.NavigableSet;
import java.util.Set;
import java.util.TreeSet;
public class SetExample {
public static void main(String[] args) {
Set<String> unique = new HashSet<>(Arrays.asList("Java", "SQL", "Java"));
System.out.println(unique.size());
System.out.println(unique.contains("Java"));
Set<String> ordered = new LinkedHashSet<>(Arrays.asList("Java", "SQL", "Java"));
System.out.println(ordered);
NavigableSet<Integer> scores = new TreeSet<>(Arrays.asList(30, 10, 20, 20));
System.out.println(scores);
System.out.println(scores.ceiling(15));
System.out.println(scores.subSet(10, true, 30, false));
}
}
Output:
2
true
[Java, SQL]
[10, 20, 30]
20
[10, 20]
subSet returns a backed view, not an independent copy. HashSet and LinkedHashSet allow one null; with natural ordering, TreeSet rejects null. A custom comparator must explicitly support null if it is needed.
6. Map and Key-Value Lookups
Each key has at most one mapped value. HashMap is a common general-purpose choice, LinkedHashMap normally preserves insertion order, and TreeMap sorts keys. An access-order LinkedHashMap is also useful for an LRU-style cache with an appropriate eviction policy.
Example: count values and sort keys
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class MapExample {
public static void main(String[] args) {
Map<String, Integer> counts = new HashMap<>();
for (String word : Arrays.asList("java", "sql", "java")) {
counts.merge(word, 1, Integer::sum);
}
System.out.println(counts.getOrDefault("java", 0));
System.out.println(counts.getOrDefault("missing", 0));
System.out.println(new TreeMap<>(counts));
}
}
Output:
2
0
{java=2, sql=1}
get(key) returning null can mean either a missing key or a key mapped to null. Use containsKey when that distinction matters. Map views such as keySet() and entrySet() are backed by the map.
7. Iteration, Copying and Sorting
Use an enhanced for loop for reading. To remove during iteration, use that iterator's remove(), or use removeIf when appropriate. Modifying many ordinary collections structurally through another path during iteration may throw ConcurrentModificationException; fail-fast detection is best effort, not a thread-safety guarantee.
Example: safe removal, sorted copy and read-only view
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class IterationExample {
public static void main(String[] args) {
List<String> items = new ArrayList<>(Arrays.asList("pear", "apple", "pear"));
Iterator<String> it = items.iterator();
while (it.hasNext()) {
if (it.next().equals("pear")) {
it.remove();
}
}
items.add("banana");
List<String> sorted = new ArrayList<>(items);
Collections.sort(sorted);
List<String> readOnly = Collections.unmodifiableList(items);
items.add("cherry");
System.out.println(sorted);
System.out.println(readOnly);
}
}
Output:
[apple, banana]
[apple, banana, cherry]
An unmodifiable view rejects changes through the view but reflects changes to its backing list. For an independent unmodifiable shallow snapshot in Java 8, use Collections.unmodifiableList(new ArrayList<>(items)). Java 10 adds List.copyOf, which rejects null elements. Arrays.asList returns a fixed-size list backed by the array; subList is also a backed view.
8. Equality, Nulls and Common Mistakes
- Hash-based collections: implement
equalsandhashCodeconsistently for custom keys and set elements. Equal objects must have equal hash codes. Do not mutate fields used in equality or hashing while an object is a key or set member. - Sorted collections: the comparator must define a consistent ordering. If it returns zero for different objects, a TreeSet treats them as the same element. Use an ordering consistent with
equalswhen normal Set/Map equality behavior is needed. - Generics: prefer
List<String>to rawListfor compile-time type safety. Use wrapper types such asInteger, not primitiveint, as type arguments. - Null policies differ: ArrayList and LinkedList permit null; ArrayDeque and PriorityQueue do not. ConcurrentHashMap allows neither null keys nor null values. Check the chosen implementation rather than assuming a framework-wide rule.
- Unmodifiable versus immutable: an unmodifiable collection can still contain mutable objects; a view may change when its backing collection changes.
9. Thread Safety and Concurrent Collections
Most general-purpose collections, including ArrayList, HashMap and HashSet, are not thread-safe for concurrent modification. Options include external locking, synchronized wrappers or a concurrent collection selected for the workload.
ConcurrentHashMapsupports concurrent access and atomic operations such asmerge. Its iterators are weakly consistent, not a snapshot.CopyOnWriteArrayListcopies its array on mutation and provides snapshot iterators; it can suit read-heavy, rarely modified lists but is expensive for frequent writes.BlockingQueueimplementations such asArrayBlockingQueuesupport producer-consumer workflows.putandtakecan block and throwInterruptedException.- When iterating a
Collections.synchronizedList, synchronize on the returned list for the entire iteration; individual synchronized method calls do not make a multi-step operation atomic.
Example: atomic counting and snapshot iteration
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
public class ConcurrentExample {
public static void main(String[] args) {
Map<String, Integer> counts = new ConcurrentHashMap<>();
counts.merge("requests", 1, Integer::sum);
counts.merge("requests", 1, Integer::sum);
System.out.println(counts.get("requests"));
CopyOnWriteArrayList<String> listeners =
new CopyOnWriteArrayList<>(Arrays.asList("first"));
Iterator<String> snapshot = listeners.iterator();
listeners.add("second");
while (snapshot.hasNext()) {
System.out.println(snapshot.next());
}
System.out.println(listeners);
}
}
Output:
2
first
[first, second]
This example demonstrates the APIs; real concurrent behavior depends on thread coordination and the atomicity of the specific operations used.
10. Performance and Practical Scenarios
The following are typical operation costs, not performance guarantees for every workload. Hash-based costs assume well-distributed hashes; amortized costs average occasional resizing over many operations.
| Implementation | Typical costs | Use case |
|---|---|---|
| ArrayList | Index access O(1); append amortized O(1); middle insertion/removal O(n). | Ordered results, indexed access. |
| LinkedList | End operations O(1); indexed access O(n). | List/deque operations at both ends. |
| ArrayDeque | End insertion/removal amortized O(1). | Request queue, undo stack, breadth-first traversal. |
| HashSet / HashMap | Add, lookup and removal expected O(1). | Deduplication or lookup by key. |
| TreeSet / TreeMap | Add, lookup and removal O(log n). | Sorted values, keys and range queries. |
| PriorityQueue | Offer and poll O(log n); peek O(1). | Process the highest- or lowest-priority task next. |
Choose based on actual access patterns, ordering requirements, memory use and synchronization. Measure realistic workloads before optimizing. For details and implementation-specific contracts, see the Java Collections API documentation and concurrent utilities.
