Java Collections Framework — Introduction
The Java Collections Framework (JCF) is a set of interfaces, implementations, and algorithms for storing and manipulating groups of objects. It’s the backbone of virtually every Java application — from simple lists of users to complex maps of configuration data.
In this chapter, you’ll learn the Collections hierarchy, the key interfaces, and how to choose the right collection for your use case.
Why Collections?
Arrays are useful but limited:
| Arrays | Collections |
|---|---|
| Fixed size | Dynamic size |
| No built-in search/sort | Rich API (sort, search, filter) |
| Only one type of structure | Lists, Sets, Maps, Queues |
| Primitive-friendly | Object-only (autoboxing for primitives) |
The Collections Framework solves all of these limitations.
The Collection Hierarchy
Iterable<T>
│
Collection<T>
/ | \
List<T> Set<T> Queue<T>
/ \ / \ \
ArrayList LinkedList HashSet TreeSet PriorityQueue
|
LinkedHashSet
Map<K,V> (separate hierarchy)
/ | \
HashMap TreeMap LinkedHashMap
Note:
Mapdoes NOT extendCollection— it’s a separate interface because it stores key-value pairs, not single elements.
Core Interfaces
| Interface | Purpose | Duplicates? | Ordered? | Example |
|---|---|---|---|---|
List<T> |
Ordered sequence | ✅ Yes | ✅ By index | ArrayList, LinkedList |
Set<T> |
Unique elements | ❌ No | ❌ (HashSet) / ✅ (TreeSet) |
HashSet, TreeSet |
Queue<T> |
FIFO processing | ✅ Yes | ✅ By insertion/priority | LinkedList, PriorityQueue |
Map<K,V> |
Key-value pairs | Keys: ❌ / Values: ✅ | ❌ (HashMap) / ✅ (TreeMap) |
HashMap, TreeMap |
Quick Examples
List — ordered, allows duplicates
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Alice"); // Duplicates allowed
System.out.println(names); // [Alice, Bob, Alice]
Set — unique elements
Set<String> tags = new HashSet<>();
tags.add("java");
tags.add("spring");
tags.add("java"); // Duplicate ignored
System.out.println(tags); // [java, spring] (order not guaranteed)
Map — key-value pairs
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 30);
ages.put("Bob", 25);
System.out.println(ages.get("Alice")); // 30
How to Choose the Right Collection
Do you need key-value pairs?
├── YES → Map
│ ├── Need sorted keys? → TreeMap
│ ├── Need insertion order? → LinkedHashMap
│ └── Otherwise → HashMap
└── NO → Collection
├── Need unique elements? → Set
│ ├── Need sorted? → TreeSet
│ └── Otherwise → HashSet
└── Allow duplicates? → List
├── Frequent random access? → ArrayList
└── Frequent insert/remove? → LinkedList
Importing Collections
All collection classes are in the java.util package:
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;
What’s Next?
In the next chapter, we’ll dive deep into the List interface — ArrayList, LinkedList, and all the methods you’ll use daily.