What is the Collections Framework?
The Java Collections Framework provides a set of classes and interfaces for storing and manipulating groups of objects. It's far more flexible than arrays.
Collections Hierarchy
Collection (interface)
├── List (ordered, allows duplicates)
│ ├── ArrayList
│ ├── LinkedList
│ └── Vector
├── Set (no duplicates)
│ ├── HashSet
│ ├── LinkedHashSet
│ └── TreeSet
└── Queue (FIFO)
├── LinkedList
└── PriorityQueue
Map (key-value pairs, separate hierarchy)
├── HashMap
├── LinkedHashMap
├── TreeMap
└── HashtableArrayList
Dynamic array — most commonly used:
java
import java.util.ArrayList;
ArrayList<String> names = new ArrayList<>();
names.add("Arjun");
names.add("Priya");
names.add("Rahul");
System.out.println(names.get(0)); // Arjun
System.out.println(names.size()); // 3
names.remove("Priya");
System.out.println(names.contains("Priya")); // false
for (String name : names) {
System.out.println(name);
}HashMap
Key-value pairs:
java
import java.util.HashMap;
HashMap<String, Integer> scores = new HashMap<>();
scores.put("Arjun", 95);
scores.put("Priya", 88);
scores.put("Rahul", 92);
System.out.println(scores.get("Arjun")); // 95
for (var entry : scores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}HashSet
Unique elements, no order guaranteed:
java
import java.util.HashSet;
HashSet<String> tags = new HashSet<>();
tags.add("java");
tags.add("oop");
tags.add("java"); // Duplicate — ignored
System.out.println(tags.size()); // 2Choosing the Right Collection
| Need | Use |
|---|---|
| Ordered list with index access | ArrayList |
| Frequent insertions/deletions | LinkedList |
| Unique elements | HashSet |
| Unique + sorted | TreeSet |
| Key-value lookup | HashMap |
| Key-value sorted by key | TreeMap |
| FIFO queue | LinkedList or ArrayDeque |
Collections Utility Methods
java
import java.util.Collections;
import java.util.ArrayList;
ArrayList<Integer> nums = new ArrayList<>(List.of(5, 2, 8, 1, 9));
Collections.sort(nums); // [1, 2, 5, 8, 9]
Collections.reverse(nums); // [9, 8, 5, 2, 1]
System.out.println(Collections.max(nums)); // 9
System.out.println(Collections.min(nums)); // 1Summary
- The Collections Framework provides dynamic, flexible alternatives to arrays
- List: ordered, allows duplicates (
ArrayList,LinkedList) - Set: no duplicates (
HashSet,TreeSet) - Map: key-value pairs (
HashMap,TreeMap) - Use generics (
ArrayList<String>) for type safety Collectionsutility class provides sorting, searching, and more