Java Generic Collections
Collections Are Built on Generics
The Collections Framework is the largest and most important user of generics in Java. Every interface and class in it is generic:
Iterable<T>
└── Collection<E>
├── List<E> → ArrayList<E>, LinkedList<E>
├── Set<E> → HashSet<E>, LinkedHashSet<E>, TreeSet<E>
└── Queue<E> → ArrayDeque<E>, PriorityQueue<E>
Map<K, V> → HashMap<K, V>, LinkedHashMap<K, V>, TreeMap<K, V>
The earlier Collections lessons showed how to use each collection. This lesson looks at them from the generics side: how type parameters flow through the framework, how generic utility methods work with them, and techniques that only make sense once you understand generics — read-only views, runtime-checked collections, nested collection types and type-safe heterogeneous containers.
Declaring Collection Variables
List<String> names = new ArrayList<>(); // declare with the interface, create with a class
Map<String, List<Order>> ordersByCity = new HashMap<>(); // nested type arguments
Set<Course> catalogue = new TreeSet<>(Comparator.comparing(Course::title));
Three conventions are worth following:
- Declare variables, fields, parameters and return types with interfaces (
List,Map,Set), and name the implementation class only when creating the object. Code that receives aList<String>works with any list implementation, and you can changeArrayListto another class in one place. - Use the diamond on the right side; the type arguments are inferred from the declaration.
- Make type arguments as specific as the data.
Map<String, Object>throws away the type information that generics exist to keep; a small record or class for the values is usually better.
Generic Collections versus Arrays
Arrays and generic collections handle types in opposite ways:
import java.util.*;
public class Arr {
public static void main(String[] args) {
Object[] objects = new String[2];
objects[0] = "Java";
try {
objects[1] = 42;
} catch (ArrayStoreException e) {
System.out.println("arrays check at runtime: ArrayStoreException " + e.getMessage());
}
List<String> names = new ArrayList<>(List.of("Asha", "Ravi"));
String[] asArray = names.toArray(String[]::new);
System.out.println("toArray: " + asArray.getClass().getSimpleName() + " " + Arrays.toString(asArray));
Object[] plain = names.toArray();
System.out.println("toArray(): " + plain.getClass().getSimpleName());
}
}
Output:
arrays check at runtime: ArrayStoreException java.lang.Integer
toArray: String[] [Asha, Ravi]
toArray(): Object[]
| Arrays | Generic collections | |
|---|---|---|
| Subtyping | Covariant: String[] is an Object[] | Invariant: List<String> is not a List<Object> |
| Element type known at runtime | Yes (reified) | No (erased) |
| Wrong element detected | At runtime (ArrayStoreException) | At compile time |
| Primitive elements | Yes (int[]) | No (List<Integer>) |
| Size | Fixed | Grows as needed |
Object[] objects = new String[2]compiles because arrays are covariant. Storing anIntegerin it fails only at runtime. The equivalent with lists (List<Object> objs = new ArrayList<String>()) doesn't compile at all.- Converting a collection to an array:
toArray(String[]::new)(Java 11+) creates an array of the right type. The no-argumenttoArray()always returnsObject[], because, due to erasure, the list doesn't know its element type.
Because the two models conflict, mixing them is awkward (generic arrays can't be created, for example). In application code, prefer collections; use arrays for primitives, fixed-size data and performance-critical code.
Generic Utility Methods
The Collections class and the factory methods on the interfaces are generic methods whose type arguments are inferred from your code:
import java.util.*;
public class Util {
public static void main(String[] args) {
List<String> none = Collections.emptyList();
List<Integer> zeros = Collections.nCopies(3, 0);
Set<String> one = Collections.singleton("admin");
System.out.println(none + " " + zeros + " " + one);
List<Number> numbers = new ArrayList<>();
Collections.addAll(numbers, 1, 2.5, 3L);
System.out.println("addAll into List<Number>: " + numbers);
Map.Entry<String, Integer> e = Map.entry("JAVA", 4999);
Map<String, Integer> fees = Map.ofEntries(e, Map.entry("PY", 2999));
System.out.println(fees.get("JAVA") + fees.get("PY"));
List<String> base = new ArrayList<>(List.of("a"));
List<String> view = Collections.unmodifiableList(base);
List<String> copy = List.copyOf(base);
base.add("b");
System.out.println("view sees change: " + view + ", copy does not: " + copy);
try {
view.add("c");
} catch (UnsupportedOperationException ex) {
System.out.println("view is read-only: UnsupportedOperationException");
}
}
}
Output:
[] [0, 0, 0] [admin]
addAll into List<Number>: [1, 2.5, 3]
7998
view sees change: [a, b], copy does not: [a]
view is read-only: UnsupportedOperationException
Collections.emptyList()has no arguments, so its type comes from the target (List<String>).nCopies(3, 0)infersIntegerfrom its argument.Collections.addAll(Collection<? super T> c, T... elements)uses a lower-bounded wildcard: integers, doubles and longs can all be added to aList<Number>.Map.entryandMap.ofEntriesbuild immutable maps with inferred key and value types, sofees.get("JAVA") + fees.get("PY")adds twoIntegers (7998).Unmodifiable view versus immutable copy:
Collections.unmodifiableList(base)returns a read-only view. It can't be modified through the view, but changes made tobaseare visible through it.List.copyOf(base)(Java 10+) creates an independent immutable copy; later changes tobasedon't affect it.
Return a view when callers should see live data but not change it; return a copy when you want a snapshot.
Runtime-Checked Collections
Generics are checked only at compile time. Raw types and unchecked casts in legacy code or libraries can still insert wrong elements (heap pollution, Type Erasure lesson), and the error then appears later, when the element is read. Collections.checkedList, checkedSet and checkedMap wrap a collection with a runtime type check on every insertion:
import java.util.*;
public class Checked {
@SuppressWarnings({"rawtypes", "unchecked"})
static void legacyAdd(List list) {
list.add(99);
}
public static void main(String[] args) {
List<String> plain = new ArrayList<>();
legacyAdd(plain);
System.out.println("plain list accepted it: " + plain);
List<String> guarded = Collections.checkedList(new ArrayList<>(), String.class);
try {
legacyAdd(guarded);
} catch (ClassCastException e) {
System.out.println("checked list rejected it: " + e.getMessage());
}
}
}
Output:
plain list accepted it: [99]
checked list rejected it: Attempt to insert class java.lang.Integer element into collection with element type class java.lang.String
The plain List<String> silently stores an Integer. The checked list receives the element type as a Class<String> token — information erasure would otherwise lose — and fails at the moment of insertion, in the code that caused the problem. Wrapping collections this way is a useful debugging technique when you suspect that some code is polluting a collection.
Nested Generic Collections
Real data often needs collections of collections: courses per student, orders per city, tags per article. Type arguments nest naturally, and the compiler tracks every level.
import java.util.*;
public class Nested {
record Enrollment(String student, String course) { }
static class EnrollmentIndex {
private final Map<String, Set<String>> coursesByStudent = new TreeMap<>();
private final Map<String, Set<String>> studentsByCourse = new TreeMap<>();
void enroll(String student, String course) {
coursesByStudent.computeIfAbsent(student, k -> new TreeSet<>()).add(course);
studentsByCourse.computeIfAbsent(course, k -> new TreeSet<>()).add(student);
}
void drop(String student, String course) {
removeFrom(coursesByStudent, student, course);
removeFrom(studentsByCourse, course, student);
}
private static <K, V> void removeFrom(Map<K, Set<V>> index, K key, V value) {
Set<V> values = index.get(key);
if (values == null) return;
values.remove(value);
if (values.isEmpty()) index.remove(key);
}
Set<String> coursesOf(String student) {
return Collections.unmodifiableSet(coursesByStudent.getOrDefault(student, Set.of()));
}
Map<String, Integer> classSizes() {
Map<String, Integer> sizes = new TreeMap<>();
studentsByCourse.forEach((course, students) -> sizes.put(course, students.size()));
return sizes;
}
Set<String> commonCourses(String a, String b) {
Set<String> result = new TreeSet<>(coursesOf(a));
result.retainAll(coursesOf(b));
return result;
}
}
public static void main(String[] args) {
List<Enrollment> data = List.of(
new Enrollment("Asha", "Java"), new Enrollment("Asha", "Docker"), new Enrollment("Asha", "Django"),
new Enrollment("Ravi", "Java"), new Enrollment("Ravi", "Docker"),
new Enrollment("Meena", "Django"));
EnrollmentIndex idx = new EnrollmentIndex();
for (Enrollment e : data) idx.enroll(e.student(), e.course());
System.out.println("Asha takes: " + idx.coursesOf("Asha"));
System.out.println("class sizes: " + idx.classSizes());
System.out.println("Asha & Ravi share: " + idx.commonCourses("Asha", "Ravi"));
idx.drop("Meena", "Django");
System.out.println("after Meena drops Django: " + idx.classSizes() + ", Meena takes " + idx.coursesOf("Meena"));
try {
idx.coursesOf("Asha").add("Rust");
} catch (UnsupportedOperationException e) {
System.out.println("callers cannot modify the index directly");
}
}
}
Output:
Asha takes: [Django, Docker, Java]
class sizes: {Django=2, Docker=2, Java=2}
Asha & Ravi share: [Docker, Java]
after Meena drops Django: {Django=1, Docker=2, Java=2}, Meena takes []
callers cannot modify the index directly
How it works:
- Two indexes (
Map<String, Set<String>>) record the many-to-many relationship in both directions, so "which courses does Asha take?" and "who is in Docker?" are both direct lookups. computeIfAbsent(key, k -> new TreeSet<>())returns the existing set for the key, or creates, stores and returns a new one. The diamond inside the lambda infersTreeSet<String>from the map's value type. This one line replaces the classic "get, check for null, create, put" sequence.- A private generic helper
removeFrom(Map<K, Set<V>>, K, V)works for both indexes, even though their roles are swapped (student → courses and course → students). It also removes keys whose set becomes empty, so the index doesn't fill up with empty entries. - Encapsulation.
coursesOfreturns an unmodifiable view, so callers can read a student's courses but can't bypassenroll/dropand break the two indexes' consistency.getOrDefault(student, Set.of())returns an empty immutable set for unknown students instead ofnull. - Set operations —
retainAllcomputes the intersection of two students' courses, on a copy so that neither index is modified.
Practical Example: A Type-Safe Heterogeneous Container
Normally a collection holds values of one type. Sometimes an application needs a container for values of many different types, each looked up by its type — for example, a per-request context holding the current user ID, the request start time, and a trace ID. A Map<Class<?>, Object> combined with generic methods keyed by Class<T> provides this with full type safety for callers (a pattern described in Effective Java).
import java.time.*;
import java.util.*;
public class Hetero {
static final class RequestContext {
private final Map<Class<?>, Object> values = new HashMap<>();
<T> void put(Class<T> type, T value) {
values.put(Objects.requireNonNull(type), type.cast(value));
}
<T> Optional<T> get(Class<T> type) {
return Optional.ofNullable(type.cast(values.get(type)));
}
}
record UserId(long value) { }
record Tenant(String name) { }
public static void main(String[] args) {
RequestContext ctx = new RequestContext();
ctx.put(UserId.class, new UserId(1001));
ctx.put(Instant.class, Instant.parse("2026-11-15T10:30:00Z"));
ctx.put(String.class, "trace-7f3a");
long id = ctx.get(UserId.class).orElseThrow().value();
Instant started = ctx.get(Instant.class).orElseThrow();
String trace = ctx.get(String.class).orElse("none");
System.out.println("user " + id + ", started " + started + ", trace " + trace.toUpperCase());
System.out.println("tenant present: " + ctx.get(Tenant.class).isPresent());
}
}
Output:
user 1001, started 2026-11-15T10:30:00Z, trace TRACE-7F3A
tenant present: false
How it works:
- The key carries the type. Instead of parameterizing the container, each key is a
Class<T>object.Classis itself generic —UserId.classhas the typeClass<UserId>— so the key tells the compiler what type the value has. put(Class<T>, T)links the key and the value through the sharedT:ctx.put(UserId.class, "oops")doesn't compile.type.cast(value)additionally checks at runtime, protecting the container against raw-type callers.get(Class<T>)returnsOptional<T>: the internal map storesObject, buttype.cast(...)converts the value back toTwith a checked cast, so callers receive aUserId, anInstantor aStringdirectly —.value()and.toUpperCase()compile without casts.- Missing values produce an empty
Optional(Tenantwas never stored), andtype.cast(null)safely returnsnull. - Small record types as keys. Storing the user ID as a
UserIdrecord instead of a bareLonggives it its own key, so differentlongvalues (a user ID, an order ID) can't collide.
The same idea underlies Spring's ApplicationContext.getBean(Class<T>), servlet attribute helpers, and dependency-injection containers — all of them map types to instances while letting callers retrieve values without casts. A limitation follows from erasure: there is no List<String>.class, so the container can't distinguish List<String> from List<Integer> keys; frameworks use the super type tokens from the Type Erasure lesson for that.