Java Generics Introduction
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:
- No type safety.
add(42)compiles, because anIntegeris anObject. Nothing stops a wrong value from entering the list. - Casts everywhere. Every value taken out is an
Objectand must be cast toStringbefore string methods can be used. - 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
Stringdirectly, because the compiler knows every element is aString. - The code documents itself.
List<String> emailssays what the list contains; a rawListdoesn'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 namedT. Inside the class,Tis used like a normal type: for the field, the parameter ofsetand the return type ofget.GenericBox<String>supplies a type argument: for this object,TmeansString.setaccepts onlyString, andgetreturnsString— no cast.GenericBox<Integer>reuses the same class for integers.count.get() + 1works becauseget()returnsInteger, which is unboxed tointautomatically.- The
ObjectBoxversion 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
| Term | Meaning | Example |
|---|---|---|
| Generic type | A class or interface with type parameters | List<E>, Map<K, V>, GenericBox<T> |
| Type parameter | The placeholder name in the declaration | T in class GenericBox<T> |
| Type argument | The actual type supplied when using it | String in GenericBox<String> |
| Parameterized type | A generic type with arguments supplied | List<String>, Map<String, Integer> |
| Raw type | A generic type used without arguments | List, 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:
| Name | Usually means |
|---|---|
T | Type (general purpose); U, S for additional types |
E | Element (collections: List<E>, Set<E>) |
K, V | Key and value (Map<K, V>) |
R | Return/result type (Function<T, R>) |
N | Number |
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:
record PageOf<T>is a generic record:Tis the item type. Its components and methods are the same for courses, students or anything else.totalPages()rounds up with integer arithmetic: 5 courses with 2 per page is(5 + 2 - 1) / 2 = 3pages.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 aList<Course>, the compiler infersT = Courseand the result is aPageOf<Course>— no casts, no type arguments written at the call site.Math.minkeeps the slice within bounds for pages past the end.p2.items()is aList<Course>, soc.code()andc.fee()are available directly. With anObject-based page, every item would need a cast.mapconverts 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 aPageOf<String>. API layers use exactly this to turn database entities into response objects (DTOs).- The same code serves students:
paginate(students, 1, 10)returnsPageOf<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.