Lesson 20 of 20
Collections and Generics
Use ArrayList, HashMap, HashSet, iterators, and generic types to manage dynamic groups of objects.
Learning objectives
- Choose between List, Set, and Map based on the problem.
- Add, retrieve, update, and remove collection elements.
- Iterate safely through collections.
- Explain why generics improve type safety.
- Create a simple generic class.
1. List: ordered values that may repeat
ArrayList is a resizable list. It keeps insertion order and permits duplicate values.
Example: ArrayList
import java.util.ArrayList;
import java.util.List;
public class ListDemo {
public static void main(String[] args) {
List<String> courses = new ArrayList<>();
courses.add("Java");
courses.add("Python");
courses.add("Java");
for (String course : courses) {
System.out.println(course);
}
}
}
2. Set: unique values
A Set prevents duplicates. HashSet is a common implementation.
import java.util.HashSet;
import java.util.Set;
Set<String> skills = new HashSet<>();
skills.add("Java");
skills.add("SQL");
skills.add("Java");
System.out.println(skills.size()); // 2
3. Map: key-value pairs
A Map associates each key with a value. Student IDs are a natural key for student records.
import java.util.HashMap;
import java.util.Map;
Map<String, String> students = new HashMap<>();
students.put("S001", "Amina");
students.put("S002", "Daniel");
System.out.println(students.get("S001"));
4. Generics
The angle-bracket type parameter tells Java which element type belongs in a collection. List<String> accepts strings and gives you strings back without manual casting.
Example: your own generic Box
public class Box<T> {
private T value;
public Box(T value) {
this.value = value;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
}
class BoxDemo {
public static void main(String[] args) {
Box<String> messageBox = new Box<>("Hello");
Box<Integer> numberBox = new Box<>(100);
System.out.println(messageBox.getValue());
System.out.println(numberBox.getValue());
}
}
Mini project: student mark lookup
import java.util.LinkedHashMap;
import java.util.Map;
public class StudentMarkLookup {
public static void main(String[] args) {
Map<String, Integer> marks = new LinkedHashMap<>();
marks.put("S001", 82);
marks.put("S002", 74);
marks.put("S003", 91);
String searchId = "S002";
if (marks.containsKey(searchId)) {
System.out.println(
searchId + " mark: " + marks.get(searchId)
);
} else {
System.out.println("Student not found.");
}
System.out.println("
All records:");
for (Map.Entry<String, Integer> entry : marks.entrySet()) {
System.out.println(
entry.getKey() + " -> " + entry.getValue()
);
}
}
}
Which collection should I choose?
| Requirement | Collection | Typical use |
|---|---|---|
| Need an ordered sequence and duplicates are allowed | List | Example: shopping items or marks. |
| Need unique values | Set | Example: unique tags or registered skills. |
| Need lookup by key | Map | Example: student ID → student record. |
Common mistakes
| Problem | Why it happens | How to fix it |
|---|---|---|
Using a raw type such as ArrayList list | Type safety is lost. | Use generics, e.g. List<String>. |
| Removing items during enhanced for loop | It can trigger concurrent modification errors. | Use an iterator or methods such as removeIf. |
| Assuming HashMap preserves insertion order | HashMap does not promise that order. | Use LinkedHashMap when insertion order matters. |
Course checkpoint
You have now progressed from Java setup and basic syntax through control flow, arrays, strings, methods, object-oriented programming, exceptions, files, and collections. A strong next step is to combine these topics into a multi-class project such as a Student Management System, then continue to lambdas, date/time APIs, streams, databases, testing, and web development.
Summary
Collections provide dynamic data structures, and generics make them type-safe. This lesson closes the first 20-lesson foundation and prepares you for more advanced Java programming.