Java Generic Collections

Su Suriya Ravichandran Updated 18 Nov 2026
9 min read ·Lesson 166 of 306

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 a List<String> works with any list implementation, and you can change ArrayList to 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[]
ArraysGeneric collections
SubtypingCovariant: String[] is an Object[]Invariant: List<String> is not a List<Object>
Element type known at runtimeYes (reified)No (erased)
Wrong element detectedAt runtime (ArrayStoreException)At compile time
Primitive elementsYes (int[])No (List<Integer>)
SizeFixedGrows as needed
  • Object[] objects = new String[2] compiles because arrays are covariant. Storing an Integer in 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-argument toArray() always returns Object[], 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) infers Integer from its argument.

  • Collections.addAll(Collection<? super T> c, T... elements) uses a lower-bounded wildcard: integers, doubles and longs can all be added to a List<Number>.

  • Map.entry and Map.ofEntries build immutable maps with inferred key and value types, so fees.get("JAVA") + fees.get("PY") adds two Integers (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 to base are visible through it.
    • List.copyOf(base) (Java 10+) creates an independent immutable copy; later changes to base don'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:

  1. 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.
  2. 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 infers TreeSet<String> from the map's value type. This one line replaces the classic "get, check for null, create, put" sequence.
  3. 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.
  4. Encapsulation. coursesOf returns an unmodifiable view, so callers can read a student's courses but can't bypass enroll/drop and break the two indexes' consistency. getOrDefault(student, Set.of()) returns an empty immutable set for unknown students instead of null.
  5. Set operations — retainAll computes 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:

  1. The key carries the type. Instead of parameterizing the container, each key is a Class<T> object. Class is itself generic — UserId.class has the type Class<UserId> — so the key tells the compiler what type the value has.
  2. put(Class<T>, T) links the key and the value through the shared T: ctx.put(UserId.class, "oops") doesn't compile. type.cast(value) additionally checks at runtime, protecting the container against raw-type callers.
  3. get(Class<T>) returns Optional<T>: the internal map stores Object, but type.cast(...) converts the value back to T with a checked cast, so callers receive a UserId, an Instant or a String directly — .value() and .toUpperCase() compile without casts.
  4. Missing values produce an empty Optional (Tenant was never stored), and type.cast(null) safely returns null.
  5. Small record types as keys. Storing the user ID as a UserId record instead of a bare Long gives it its own key, so different long values (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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Generic Collections and get answers drawn from it.

Signed-in readers only.