Java Generic Types
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:
- Multiple parameters.
Pair<A, B>has two independent type parameters.Pair<String, Integer>fixesA = StringandB = Integer, sofirst()returns aStringandsecond()anInteger(unboxed tointwhen assigned toqty). - Constructors don't repeat the parameters. The constructor is written
Pair(A first, B second), notPair<A, B>(...); the class's type parameters are already in scope. - Using the parameters in other types.
swap()returnsPair<B, A>— the same class with the arguments reversed. Inside the class,new Pair<>(second, first)lets the diamond infer<B, A>. - Type arguments can themselves be generic.
Pair<String, List<String>>andMap<String, Pair<Integer, Double>>nest generic types; the compiler tracks every level, sop.first()is known to be anIntegerwithout any casts. - Generic records.
record Range<T ...>(T min, T max)declares type parameters the same way; the components useT. The compact constructor validates thatminisn't greater thanmax. - A bound.
T extends Comparable<T>restrictsTto types that can be compared, which is what makescompareTocallable onmin,maxandvalue.Range<Integer>andRange<String>work because both types implementComparable. 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 allowed | Why | Usual workaround |
|---|---|---|
static T field / using T in static methods | Static members belong to the class, shared by Holder<String> and Holder<Integer> alike, so there is no single T | Make 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 constructor | Pass a factory: Supplier<T> (Holder<>(ArrayList::new)) or a Class<T> |
new T[n] | Arrays need their exact element type at runtime | Use a List<T>, or create the array from a Class<T> / an IntFunction<T[]> (String[]::new) |
o instanceof T, (T) o checked casts | The runtime can't check against an unknown type | Keep a Class<T> and use type.isInstance(o) / type.cast(o) |
Primitive type arguments (Holder<int>) | Type arguments must be reference types | Use 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>fixesT = CourseandID = String. The subclass isn't generic itself; it inheritssave(String, Course),findById(String)and so on, and adds a method that usesCourse'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@Overrideuses the type parameters in its signature, matching the parent's method.- Subtyping follows the class hierarchy: a
CourseRepositoryis aRepository<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:
ExpiringCache<K, V>has a key type and a value type. All fields and methods use them: the map isMap<K, Entry<V>>,gettakes aKand returns aV.- A private generic record
Entry<V>stores each value with its expiry time. Its type parameterVis separate from the outer class'sV(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. Function<K, V> loaderis 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).- Hits and expiry. The second
USD/INRrequest 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. - A test clock. The cache asks a
java.time.Clockfor the current time instead of callingInstant.now()directly. The test subclass returns a time the test controls, so expiry can be demonstrated instantly and deterministically. In production you'd passClock.systemUTC(). - Reuse with other types.
ExpiringCache<Integer, String>caches user names by ID. Becausegetreturns aString,.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.