Module 9 · Collections and Generics — topic 1 of 5
The Collections Framework
An overview of the Collection interfaces and their main implementations, choosing the right collection, immutable collections, and the Collections utility class.
Learning objectives
- Name the core collection interfaces and what each guarantees
- Choose an implementation by its ordering and performance
- Use immutable factory methods and the Collections utility class
Definition
The Java Collections Framework is a set of interfaces (Collection, List, Set, Queue, Deque, Map) and implementations (ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap, ArrayDeque, PriorityQueue and others) for storing and processing groups of objects.
Introduction
Arrays have a fixed size and few built-in operations. Real programs need groups of data that grow, shrink, stay sorted, reject duplicates or answer 'what is the value for this key?' quickly. The Collections Framework provides a well-designed toolbox for all of these, and it is used in practically every Java program.
Why it matters
Picking the right collection is often the difference between a program that is instant and one that is unusably slow.
Collections questions — HashMap internals, ArrayList vs LinkedList — are among the most common Java interview topics.
Detailed explanation
List — an ordered sequence with indexes that allows duplicates. ArrayList (resizable array: fast random access, fast append) is the default; LinkedList is rarely better in practice.
Set — no duplicates. HashSet (fast, no order), LinkedHashSet (keeps insertion order), TreeSet (sorted, O(log n)).
Map — key-to-value pairs with unique keys (not a subtype of Collection). HashMap (fast, no order), LinkedHashMap (insertion order), TreeMap (sorted keys).
Queue and Deque — ArrayDeque works as both a FIFO queue (offer/poll) and a LIFO stack (push/pop), and is preferred over the legacy Stack class. PriorityQueue always gives you the smallest element first (a min-heap).
Program to interfaces. Declare variables with the interface type — List<String> names = new ArrayList<>(); — so you can switch implementations without changing other code.
Immutable collections (Java 9+). List.of(...), Set.of(...) and Map.of(...) create compact unmodifiable collections; List.copyOf makes an unmodifiable copy. Modifying them throws UnsupportedOperationException, and they don't allow null elements.
java.util.Collections offers static helpers: sort, reverse, shuffle, max, min, frequency, unmodifiableList, nCopies and emptyList.
Collections hold objects only, so primitives are autoboxed (List<Integer>).
Syntax
- The diamond
<>lets the compiler infer the type arguments. - HashMap/HashSet need correct equals and hashCode; TreeMap/TreeSet need comparable elements or a Comparator.
- Most collections are not thread-safe; see java.util.concurrent for shared use.
Code examples
One task, four collections
List: [pear, apple, fig, apple, kiwi, fig] size 6 HashSet size: 4 (order not guaranteed) LinkedHashSet: [pear, apple, fig, kiwi] TreeSet: [apple, fig, kiwi, pear] frequency of apple: 2, max: pear
Stacks, queues and priority queues
back from page3 to page2 serving Asha, next Ravi, waiting 2 by priority: 1 2 3 4 5
More examples
Immutability, views and performance
List.of is unmodifiable
view sees backing changes: [C, Java, Python, Go]
found 1000 and 1000; HashSet lookups faster: true
{a=[avocado, apple], b=[banana, blueberry], c=[cherry]}Step-by-step explanation
List.ofcreates an unmodifiable list, soaddthrows UnsupportedOperationException.Collections.unmodifiableListis a read-only *view*: callers can't modify it, but changes to the backing list show through.list.containsscans the ArrayList element by element (O(n)), whileset.containshashes straight to the right bucket (O(1) on average); with 200,000 elements the difference is dramatic.computeIfAbsentcreates the inner list the first time a letter is seen, thenaddappends the word — a standard grouping pattern.- The TreeMap prints its keys in sorted order, while each list keeps the order in which the words were added.
Expected output
Running “Immutability, views and performance” prints exactly:
Practical applications
- HashMap for caches, lookups by id and counting
- ArrayList for most ordered data shown to users
- ArrayDeque for undo stacks and BFS queues
- PriorityQueue for schedulers and Dijkstra's algorithm
Best practices
- Default to ArrayList, HashMap and HashSet; choose Linked/Tree variants when you need their ordering.
- Use List.of/Set.of/Map.of for fixed data.
- Use ArrayDeque instead of Stack and LinkedList for stacks and queues.
Common mistakes
Declaring with the implementation type
Avoid
Prefer
Using the interface keeps code flexible and makes it easy to swap implementations.
Using List.contains for frequent lookups
Avoid
Prefer
contains on a list is linear, making the whole loop quadratic; a HashSet makes each check constant time.
Important notes
- HashSet and HashMap iteration order is unspecified and may differ between Java versions — never rely on it.
- Vector, Stack and Hashtable are legacy synchronised classes; avoid them in new code.
Key takeaways
- List = ordered with duplicates; Set = unique; Map = key to value; Deque = stack or queue.
- Choose implementations by ordering needs and performance.
- Program to interfaces and use immutable factories for fixed data.
Try it yourself
- 1Remove duplicates from a list of names while keeping their original order.
- 2Use an ArrayDeque to check whether brackets in a string such as "{[()]}" are balanced.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
3 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhich collection does not allow duplicate elements?
- ModerateWhat is printed?
- ModerateWhat is printed?