Java Generic Types

Su Suriya Ravichandran Updated 18 Nov 2026
10 min read ·Lesson 160 of 306

Declaring a Generic Class

A generic type is a class, interface or record declared with one or more type parameters in angle brackets after its name:

class Pair<A, B> { ... }          // two type parameters
record Range<T extends Comparable<T>>(T min, T max) { ... }
interface Repository<T, ID> { ... }

Inside the declaration, each type parameter can be used almost anywhere a type is expected: field types, constructor and method parameters, return types, local variables, and as type arguments to other generic types (List<T>). When someone uses the class, they supply type arguments, and every occurrence of the parameter takes on that type for that object.

You write a generic type when a class's logic is the same regardless of the type of data it holds — containers, pairs, caches, repositories, result wrappers, pages of results — but users of the class should still get compile-time type checking and no casts.

A Class with Two Type Parameters

import java.util.*;

public class Pairs {
    static class Pair<A, B> {
        private final A first;
        private final B second;

        Pair(A first, B second) {
            this.first = first;
            this.second = second;
        }

        A first() { return first; }
        B second() { return second; }
        Pair<B, A> swap() { return new Pair<>(second, first); }

        @Override public String toString() { return "(" + first + ", " + second + ")"; }
    }

    record Range<T extends Comparable<T>>(T min, T max) {
        Range {
            if (min.compareTo(max) > 0) throw new IllegalArgumentException(min + " > " + max);
        }
        boolean contains(T value) { return value.compareTo(min) >= 0 && value.compareTo(max) <= 0; }
    }

    public static void main(String[] args) {
        Pair<String, Integer> stock = new Pair<>("PEN-01", 40);
        String sku = stock.first();
        int qty = stock.second();
        System.out.println(stock + " -> sku=" + sku + ", qty=" + qty + ", swapped=" + stock.swap());

        Pair<String, List<String>> course = new Pair<>("Java", List.of("Generics", "Streams"));
        System.out.println(course.first() + " has " + course.second().size() + " modules");

        Map<String, Pair<Integer, Double>> report = new TreeMap<>();
        report.put("Java", new Pair<>(120, 4.8));
        report.put("Django", new Pair<>(85, 4.6));
        report.forEach((name, p) -> System.out.println(name + ": " + p.first() + " students, rating " + p.second()));

        Range<Integer> working = new Range<>(9, 18);
        System.out.println("10 in " + working + ": " + working.contains(10));
        Range<String> aToM = new Range<>("A", "M");
        System.out.println("\"Kumar\" in A-M: " + aToM.contains("Kumar"));
    }
}

Output:

(PEN-01, 40) -> sku=PEN-01, qty=40, swapped=(40, PEN-01)
Java has 2 modules
Django: 85 students, rating 4.6
Java: 120 students, rating 4.8
10 in Range[min=9, max=18]: true
"Kumar" in A-M: true

What each part shows:

  1. Multiple parameters. Pair<A, B> has two independent type parameters. Pair<String, Integer> fixes A = String and B = Integer, so first() returns a String and second() an Integer (unboxed to int when assigned to qty).
  2. Constructors don't repeat the parameters. The constructor is written Pair(A first, B second), not Pair<A, B>(...); the class's type parameters are already in scope.
  3. Using the parameters in other types. swap() returns Pair<B, A> — the same class with the arguments reversed. Inside the class, new Pair<>(second, first) lets the diamond infer <B, A>.
  4. Type arguments can themselves be generic. Pair<String, List<String>> and Map<String, Pair<Integer, Double>> nest generic types; the compiler tracks every level, so p.first() is known to be an Integer without any casts.
  5. Generic records. record Range<T ...>(T min, T max) declares type parameters the same way; the components use T. The compact constructor validates that min isn't greater than max.
  6. A bound. T extends Comparable<T> restricts T to types that can be compared, which is what makes compareTo callable on min, max and value. Range<Integer> and Range<String> work because both types implement Comparable. Bounds are the subject of the Bounded Types lesson.

The Diamond Operator

Pair<String, Integer> p1 = new Pair<String, Integer>("PEN-01", 40); // explicit (Java 5 style)
Pair<String, Integer> p2 = new Pair<>("PEN-01", 40);                // diamond (Java 7+)
var p3 = new Pair<>("PEN-01", 40);                                  // var + diamond: inferred from the arguments

The diamond <> tells the compiler to infer the type arguments — from the variable's declared type, or from the constructor arguments. With var, there's no declared type, so inference uses the constructor arguments (Pair<String, Integer> here). Be careful with var and an empty diamond: var list = new ArrayList<>(); infers ArrayList<Object>, which loses the type safety you wanted. Since Java 9 the diamond also works with anonymous classes.

What You Can't Do with a Type Parameter

Type parameters exist only at compile time; at runtime, the JVM doesn't know what T was for a particular object (the Type Erasure lesson explains why). That makes a few operations impossible:

public class Errors {
    static class Holder<T> {
        static T shared;
        T create() { return new T(); }
        T[] array() { return new T[10]; }
        boolean check(Object o) { return o instanceof T; }
    }
}

Compiler output:

Errors.java:3: error: non-static type variable T cannot be referenced from a static context
        static T shared;
               ^
Errors.java:4: error: unexpected type
        T create() { return new T(); }
                                ^
  required: class
  found:    type parameter T
  where T is a type-variable:
    T extends Object declared in class Holder
Errors.java:5: error: generic array creation
        T[] array() { return new T[10]; }
                             ^
Errors.java:6: error: Object cannot be safely cast to T
        boolean check(Object o) { return o instanceof T; }
                                         ^
  where T is a type-variable:
    T extends Object declared in class Holder
4 errors
Not allowedWhyUsual workaround
static T field / using T in static methodsStatic members belong to the class, shared by Holder<String> and Holder<Integer> alike, so there is no single TMake the static method generic itself: static <T> ...
new T()The runtime doesn't know which class T is, or whether it has a no-argument constructorPass a factory: Supplier<T> (Holder<>(ArrayList::new)) or a Class<T>
new T[n]Arrays need their exact element type at runtimeUse a List<T>, or create the array from a Class<T> / an IntFunction<T[]> (String[]::new)
o instanceof T, (T) o checked castsThe runtime can't check against an unknown typeKeep a Class<T> and use type.isInstance(o) / type.cast(o)
Primitive type arguments (Holder<int>)Type arguments must be reference typesUse the wrapper class (Holder<Integer>)

Generic Types and Inheritance

A generic class can be extended in two ways: by fixing its type arguments, or by passing them through as parameters of the subclass.

import java.util.*;

public class Inherit {
    static class Repository<T, ID> {
        protected final Map<ID, T> store = new LinkedHashMap<>();
        void save(ID id, T item) { store.put(id, item); }
        Optional<T> findById(ID id) { return Optional.ofNullable(store.get(id)); }
        List<T> findAll() { return new ArrayList<>(store.values()); }
    }

    record Course(String code, String title) { }

    static class CourseRepository extends Repository<Course, String> {
        List<Course> findByTitleContaining(String text) {
            List<Course> result = new ArrayList<>();
            for (Course c : store.values()) if (c.title().contains(text)) result.add(c);
            return result;
        }
    }

    static class AuditedRepository<T, ID> extends Repository<T, ID> {
        final List<String> log = new ArrayList<>();
        @Override void save(ID id, T item) {
            log.add("save " + id);
            super.save(id, item);
        }
    }

    public static void main(String[] args) {
        CourseRepository courses = new CourseRepository();
        courses.save("JAVA", new Course("JAVA", "Java Programming"));
        courses.save("JS", new Course("JS", "JavaScript Programming"));
        courses.save("DOCK", new Course("DOCK", "Docker Essentials"));
        System.out.println(courses.findById("JS").map(Course::title).orElse("none"));
        System.out.println(courses.findByTitleContaining("Programming").size() + " programming courses");

        AuditedRepository<String, Integer> notes = new AuditedRepository<>();
        notes.save(1, "first");
        notes.save(2, "second");
        System.out.println(notes.findAll() + " " + notes.log);

        Repository<Course, String> general = courses;
        System.out.println("as Repository: " + general.findAll().size() + " items");
    }
}

Output:

JavaScript Programming
2 programming courses
[first, second] [save 1, save 2]
as Repository: 3 items
  • CourseRepository extends Repository<Course, String> fixes T = Course and ID = String. The subclass isn't generic itself; it inherits save(String, Course), findById(String) and so on, and adds a method that uses Course's fields. This is the common pattern for specialising generic infrastructure for one entity type.
  • AuditedRepository<T, ID> extends Repository<T, ID> stays generic and passes its own parameters to the parent. It adds behaviour (logging) that works for any entity type. The @Override uses the type parameters in its signature, matching the parent's method.
  • Subtyping follows the class hierarchy: a CourseRepository is a Repository<Course, String>, so it can be assigned to that type.

Generic types are invariant

The class hierarchy of the type arguments doesn't carry over to the generic types:

import java.util.*;

public class Invariant {
    public static void main(String[] args) {
        List<Integer> ints = new ArrayList<>(List.of(1, 2, 3));
        List<Number> nums = ints;
    }
}
Invariant.java:6: error: incompatible types: List<Integer> cannot be converted to List<Number>
        List<Number> nums = ints;
                            ^
1 error

Even though Integer is a subclass of Number, List<Integer> is not a subtype of List<Number>. If it were, nums.add(3.5) would be allowed and would put a Double into a list of integers. This rule — called invariance — keeps generic types safe. Wildcards (List<? extends Number>) provide the flexibility to accept "a list of any kind of number" safely; they're covered in the Wildcards lesson.

Practical Example: A Generic Expiring Cache

Applications cache data that is expensive to fetch — exchange rates from an external API, user profiles from a database — but cached values must expire so they don't become stale. The caching logic is identical for every kind of key and value, so it's naturally a generic class with two type parameters.

import java.time.*;
import java.util.*;
import java.util.function.Function;

public class Cache {
    static class ExpiringCache<K, V> {
        private record Entry<V>(V value, Instant expiresAt) { }

        private final Map<K, Entry<V>> entries = new HashMap<>();
        private final Duration timeToLive;
        private final Clock clock;
        private int hits, misses;

        ExpiringCache(Duration timeToLive, Clock clock) {
            this.timeToLive = timeToLive;
            this.clock = clock;
        }

        V get(K key, Function<K, V> loader) {
            Instant now = clock.instant();
            Entry<V> e = entries.get(key);
            if (e != null && now.isBefore(e.expiresAt())) {
                hits++;
                return e.value();
            }
            misses++;
            V value = loader.apply(key);
            entries.put(key, new Entry<>(value, now.plus(timeToLive)));
            return value;
        }

        String stats() { return "hits=" + hits + " misses=" + misses + " size=" + entries.size(); }
    }

    static class TestClock extends Clock {
        Instant now = Instant.parse("2026-11-15T10:00:00Z");
        @Override public ZoneId getZone() { return ZoneOffset.UTC; }
        @Override public Clock withZone(ZoneId zone) { return this; }
        @Override public Instant instant() { return now; }
    }

    record ExchangeRate(String pair, double rate) { }

    public static void main(String[] args) {
        TestClock clock = new TestClock();
        ExpiringCache<String, ExchangeRate> rates = new ExpiringCache<>(Duration.ofMinutes(5), clock);
        int[] apiCalls = {0};
        Function<String, ExchangeRate> fetch = pair -> {
            apiCalls[0]++;
            return new ExchangeRate(pair, pair.equals("USD/INR") ? 83.42 + apiCalls[0] * 0.01 : 90.10);
        };

        System.out.println(rates.get("USD/INR", fetch));
        System.out.println(rates.get("USD/INR", fetch));
        System.out.println(rates.get("EUR/INR", fetch));
        clock.now = clock.now.plus(Duration.ofMinutes(6));
        System.out.println(rates.get("USD/INR", fetch));
        System.out.println(rates.stats() + ", API calls=" + apiCalls[0]);

        ExpiringCache<Integer, String> userNames = new ExpiringCache<>(Duration.ofHours(1), clock);
        System.out.println(userNames.get(42, id -> "user-" + id).toUpperCase());
    }
}

Output:

ExchangeRate[pair=USD/INR, rate=83.43]
ExchangeRate[pair=USD/INR, rate=83.43]
ExchangeRate[pair=EUR/INR, rate=90.1]
ExchangeRate[pair=USD/INR, rate=83.45]
hits=1 misses=3 size=2, API calls=3
USER-42

How it works:

  1. ExpiringCache<K, V> has a key type and a value type. All fields and methods use them: the map is Map<K, Entry<V>>, get takes a K and returns a V.
  2. A private generic record Entry<V> stores each value with its expiry time. Its type parameter V is separate from the outer class's V (a nested record is implicitly static, so it can't use the outer class's type parameters directly); it's given the same name because it represents the same thing.
  3. Function<K, V> loader is a generic functional interface: a function from a key to a value. On a cache miss, the cache calls it to fetch the real value; the caller decides how (an API call, a database query).
  4. Hits and expiry. The second USD/INR request is served from the cache (same rate, no API call). After the test clock is moved forward 6 minutes — past the 5-minute time-to-live — the entry is expired, so the loader runs again and returns a fresh rate.
  5. A test clock. The cache asks a java.time.Clock for the current time instead of calling Instant.now() directly. The test subclass returns a time the test controls, so expiry can be demonstrated instantly and deterministically. In production you'd pass Clock.systemUTC().
  6. Reuse with other types. ExpiringCache<Integer, String> caches user names by ID. Because get returns a String, .toUpperCase() can be called on the result directly.

Production caches (Caffeine, Guava's Cache, Spring's caching abstraction) are generic types with the same <K, V> shape, plus features such as size limits and thread safety. This simple version isn't thread-safe; a shared cache in a server would use a ConcurrentHashMap and its compute methods.

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 Types and get answers drawn from it.

Signed-in readers only.