Java Generics Introduction

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

What Generics Are

Generics let you write classes, interfaces and methods that work with a type chosen by whoever uses them, while the compiler still checks that the right type is used everywhere.

You've used generics since the Collections lessons:

List<String> names = new ArrayList<>();
Map<String, Integer> stock = new HashMap<>();

List is written once, but it can be a list of String, a list of Integer or a list of Course. The type in angle brackets, <String>, tells the compiler what this particular list holds, and the compiler then refuses anything else and removes the need for casts.

Generics were added in Java 5 (2004). To understand why they matter, it helps to see what Java code looked like before them.

The Problem: Collections of Object

Before Java 5, collections stored Object, the parent of every class:

import java.util.*;

public class OldStyle {
    @SuppressWarnings({"rawtypes", "unchecked"})
    public static void main(String[] args) {
        List emails = new ArrayList();
        emails.add("asha@gocourse.in");
        emails.add("ravi@gocourse.in");
        emails.add(42);                                  // compiles: anything is an Object

        for (Object o : emails) {
            String email = (String) o;                   // cast needed everywhere
            System.out.println(email.toUpperCase());
        }
    }
}

Output:

ASHA@GOCOURSE.IN
RAVI@GOCOURSE.IN
Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')
	at OldStyle.main(OldStyle.java:12)

Three problems are visible:

  1. No type safety. add(42) compiles, because an Integer is an Object. Nothing stops a wrong value from entering the list.
  2. Casts everywhere. Every value taken out is an Object and must be cast to String before string methods can be used.
  3. Errors appear late and far away. The mistake is on line 9 (adding 42), but the program fails on line 12 (the cast), at runtime, possibly long after and in a completely different part of a large program.

(The @SuppressWarnings annotation only silences the compiler warnings that modern Java gives for this old style.)

The Solution: Type Parameters

import java.util.*;

public class NewStyle {
    public static void main(String[] args) {
        List<String> emails = new ArrayList<>();
        emails.add("asha@gocourse.in");
        emails.add("ravi@gocourse.in");
        emails.add(42);

        for (String email : emails) {
            System.out.println(email.toUpperCase());
        }
    }
}

Compiler output:

NewStyle.java:8: error: incompatible types: int cannot be converted to String
        emails.add(42);
                   ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

With List<String>:

  • The mistake is caught at compile time, on the exact line where it happens. The program can't even run with the bug in it.
  • No casts are needed. The loop variable is a String directly, because the compiler knows every element is a String.
  • The code documents itself. List<String> emails says what the list contains; a raw List doesn't.

That's the central idea of generics: move type errors from runtime to compile time.

Writing a Generic Class

Here's the same idea in a class you write yourself — a simple container for one value:

public class Box {
    static class ObjectBox {
        private Object value;
        void set(Object value) { this.value = value; }
        Object get() { return value; }
    }

    static class GenericBox<T> {
        private T value;
        void set(T value) { this.value = value; }
        T get() { return value; }
    }

    public static void main(String[] args) {
        ObjectBox ob = new ObjectBox();
        ob.set("Java");
        String s1 = (String) ob.get();

        GenericBox<String> gb = new GenericBox<>();
        gb.set("Java");
        String s2 = gb.get();

        GenericBox<Integer> count = new GenericBox<>();
        count.set(21);
        int next = count.get() + 1;

        System.out.println(s1 + " " + s2 + " " + next);
    }
}

Output:

Java Java 22
  • class GenericBox<T> declares a type parameter named T. Inside the class, T is used like a normal type: for the field, the parameter of set and the return type of get.
  • GenericBox<String> supplies a type argument: for this object, T means String. set accepts only String, and get returns String — no cast.
  • GenericBox<Integer> reuses the same class for integers. count.get() + 1 works because get() returns Integer, which is unboxed to int automatically.
  • The ObjectBox version works too, but requires a cast and would accept any value.

One class, written once, serves every type safely. The next lessons cover writing generic classes (Generic Types), methods (Generic Methods) and interfaces (Generic Interfaces) in detail.

Terminology

TermMeaningExample
Generic typeA class or interface with type parametersList<E>, Map<K, V>, GenericBox<T>
Type parameterThe placeholder name in the declarationT in class GenericBox<T>
Type argumentThe actual type supplied when using itString in GenericBox<String>
Parameterized typeA generic type with arguments suppliedList<String>, Map<String, Integer>
Raw typeA generic type used without argumentsList, ArrayList
Diamond <>Lets the compiler infer the arguments (Java 7+)new ArrayList<>()

Naming conventions

Type parameters are single uppercase letters by convention, which makes them easy to tell apart from real class names:

NameUsually means
TType (general purpose); U, S for additional types
EElement (collections: List<E>, Set<E>)
K, VKey and value (Map<K, V>)
RReturn/result type (Function<T, R>)
NNumber

Type arguments must be reference types

Generics work with classes, not primitives: List<int> doesn't compile; you write List<Integer>. Autoboxing converts between int and Integer automatically when you add and read values, as the GenericBox<Integer> example showed. (Specialised primitive streams like IntStream exist partly to avoid that boxing cost for large amounts of numeric data.)

Raw Types: Why to Avoid Them

A raw type is a generic type used without type arguments — List instead of List<String>. Java still allows raw types so that pre-Java-5 code keeps compiling, but using them switches off the type checks:

import java.util.*;

public class Raw {
    static void addLegacy(List list) {
        list.add(99);
    }

    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of("Asha"));
        addLegacy(names);
        System.out.println("size: " + names.size());
        String last = names.get(1);
        System.out.println(last);
    }
}

By default, the compiler only prints a short note:

Note: Raw.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

With javac -Xlint:rawtypes,unchecked Raw.java, it shows exactly where the problems are:

Raw.java:4: warning: [rawtypes] found raw type: List
    static void addLegacy(List list) {
                          ^
  missing type arguments for generic class List<E>
  where E is a type-variable:
    E extends Object declared in interface List
Raw.java:5: warning: [unchecked] unchecked call to add(E) as a member of the raw type List
        list.add(99);
                ^
  where E is a type-variable:
    E extends Object declared in interface List
2 warnings

And running it:

size: 2
Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')
	at Raw.main(Raw.java:12)

The method with the raw List parameter put an Integer into a List<String>. This is called heap pollution: a variable of a parameterized type refers to an object that contains the wrong type. It isn't detected when it happens, only later, when the value is read as a String. Treat "unchecked" warnings as real problems; enabling -Xlint:all (or the equivalent compiler setting in Maven/Gradle) makes them visible.

Raw types are acceptable in only a few places, such as class literals (List.class) and instanceof checks (obj instanceof List<?> is preferred, but obj instanceof List is also allowed).

Practical Example: A Generic Page of Results

Web APIs return large result sets in pages: page 2 of the course list, page 1 of the student list. The paging logic — slicing the list, counting pages, checking for a next page — is identical whatever the items are. With generics it's written once and works for every item type, with full type safety.

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

public class Page {
    record Course(String code, String title, int fee) { }
    record Student(String name, String city) { }

    record PageOf<T>(List<T> items, int pageNumber, int pageSize, int totalItems) {
        int totalPages() { return (totalItems + pageSize - 1) / pageSize; }
        boolean hasNext() { return pageNumber < totalPages(); }

        <R> PageOf<R> map(Function<T, R> converter) {
            List<R> converted = new ArrayList<>();
            for (T item : items) converted.add(converter.apply(item));
            return new PageOf<>(converted, pageNumber, pageSize, totalItems);
        }
    }

    static <T> PageOf<T> paginate(List<T> all, int pageNumber, int pageSize) {
        int from = Math.min((pageNumber - 1) * pageSize, all.size());
        int to = Math.min(from + pageSize, all.size());
        return new PageOf<>(List.copyOf(all.subList(from, to)), pageNumber, pageSize, all.size());
    }

    public static void main(String[] args) {
        List<Course> courses = List.of(
            new Course("JAVA", "Java Programming", 4999), new Course("PY", "Python Basics", 2999),
            new Course("DJ", "Django Web", 5999), new Course("DOCK", "Docker Essentials", 3999),
            new Course("JS", "JavaScript", 3499));
        List<Student> students = List.of(new Student("Asha", "Chennai"), new Student("Ravi", "Madurai"));

        PageOf<Course> p2 = paginate(courses, 2, 2);
        System.out.println("page " + p2.pageNumber() + " of " + p2.totalPages() + ", hasNext=" + p2.hasNext());
        for (Course c : p2.items()) System.out.println("  " + c.code() + " - Rs " + c.fee());

        PageOf<String> titles = p2.map(Course::title);
        System.out.println("titles: " + titles.items());

        PageOf<Student> s1 = paginate(students, 1, 10);
        System.out.println("students: " + s1.items().get(0).city() + ", pages=" + s1.totalPages());
    }
}

Output:

page 2 of 3, hasNext=true
  DJ - Rs 5999
  DOCK - Rs 3999
titles: [Django Web, Docker Essentials]
students: Chennai, pages=1

How generics make this work:

  1. record PageOf<T> is a generic record: T is the item type. Its components and methods are the same for courses, students or anything else.
  2. totalPages() rounds up with integer arithmetic: 5 courses with 2 per page is (5 + 2 - 1) / 2 = 3 pages.
  3. static <T> PageOf<T> paginate(List<T> all, ...) is a generic method: the <T> before the return type declares its own type parameter. When called with a List<Course>, the compiler infers T = Course and the result is a PageOf<Course> — no casts, no type arguments written at the call site. Math.min keeps the slice within bounds for pages past the end.
  4. p2.items() is a List<Course>, so c.code() and c.fee() are available directly. With an Object-based page, every item would need a cast.
  5. map converts a page of one type into a page of another, keeping the paging information. <R> is a second type parameter for the result: p2.map(Course::title) produces a PageOf<String>. API layers use exactly this to turn database entities into response objects (DTOs).
  6. The same code serves students: paginate(students, 1, 10) returns PageOf<Student>, and .city() is available directly.

Frameworks use the same design: Spring Data's Page<T> and its map method work just like this record.

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

Signed-in readers only.