Generics let you write a class or method once and use it safely with many types. When you write List<String>, you are using generics: the compiler knows the list holds only strings, rejects anything else, and removes the need for casts. This lesson shows how to write your own generic classes and methods, how bounds and wildcards work, and what type erasure means.
In this lesson you will learn
- Why generics exist: type safety without casts
- Generic classes such as
Box<T>andPair<K, V> - Generic methods
- Bounded types with
extends - Wildcards
?,? extendsand? super
Generic Classes and Methods
import java.util.List;
class Box<T> { // T is a type parameter
private T value;
Box(T value) { this.value = value; }
T get() { return value; }
void set(T value) { this.value = value; }
}
class Pair<K, V> {
final K key; final V value;
Pair(K key, V value) { this.key = key; this.value = value; }
public String toString() { return "(" + key + ", " + value + ")"; }
}
public class Main {
// Generic method: works for a list of any type
static <T> T firstOrDefault(List<T> list, T fallback) {
return list.isEmpty() ? fallback : list.get(0);
}
public static void main(String[] args) {
Box<String> name = new Box<>("Nadia");
Box<Integer> age = new Box<>(21);
String n = name.get(); // no cast needed
int a = age.get() + 1; // auto-unboxing
System.out.println(n + " will be " + a);
// name.set(42); // compile error: wrong type
Pair<String, Double> p = new Pair<>("cgpa", 3.82);
System.out.println(p);
System.out.println(firstOrDefault(List.of(5, 9), -1));
System.out.println(firstOrDefault(List.<String>of(), "none"));
}
}
Output
Nadia will be 22
(cgpa, 3.82)
5
none
class Box<T>declares a type parameterT. It is a placeholder that becomes a real type when the class is used, such asBox<String>.- Because the compiler knows
nameholds aString,name.get()needs no cast, andname.set(42)would be rejected at compile time rather than failing later at run time. - A class can have several parameters:
Pair<K, V>. Common names areT(type),E(element),KandV(key and value). - A generic method declares its own type parameter before the return type:
static <T> T firstOrDefault(...). Java usually infersTfrom the arguments. - Type parameters must be reference types:
Box<int>is not allowed, butBox<Integer>is, and autoboxing converts values for you.
Bounded Types and Wildcards
import java.util.List;
public class Main {
// Bounded type: T must be a Comparable of itself
static <T extends Comparable<T>> T largest(List<T> items) {
T best = items.get(0);
for (T x : items) if (x.compareTo(best) > 0) best = x;
return best;
}
// Upper-bounded wildcard: read numbers of any Number subtype
static double sum(List<? extends Number> nums) {
double s = 0;
for (Number x : nums) s += x.doubleValue();
return s;
}
public static void main(String[] args) {
System.out.println(largest(List.of(4, 17, 9)));
System.out.println(largest(List.of("pear", "apple", "mango")));
System.out.println(sum(List.of(1, 2, 3)));
System.out.println(sum(List.of(1.5, 2.25)));
}
}
Output
17
pear
6.0
3.75
<T extends Comparable<T>>is a bounded type:Tcan be any type that can be compared with itself, so the method may callcompareTo. It works for integers and strings alike.List<? extends Number>accepts a list ofInteger,Doubleor any otherNumbersubtype. You can read elements asNumber, but you cannot add to such a list.- A
List<Integer>is not aList<Number>, even thoughIntegeris aNumber. Wildcards exist to bridge this gap.
| Syntax | Meaning | Typical use |
|---|---|---|
List<?> | A list of some unknown type | Printing or counting any list |
List<? extends T> | T or a subtype | Reading values out (a producer) |
List<? super T> | T or a supertype | Writing values in (a consumer) |
A memory aid is PECS: Producer Extends, Consumer Super.
Type Erasure
Generics are checked by the compiler and then removed from the compiled code; at run time a List<String> and a List<Integer> are both just List. As a result you cannot write new T(), new T[10] or obj instanceof List<String>.
Common Mistakes
- Using raw types such as
List list = new ArrayList();, which turns off type checking and causes warnings. - Expecting
List<Integer>to be accepted whereList<Number>is required; useList<? extends Number>. - Using primitives as type arguments.
- Trying to create
new T(), which erasure makes impossible.
Practice Exercises
Exercise 1. Write a generic method swap that swaps two elements of an array of any reference type.
Show answer
static <T> void swap(T[] arr, int i, int j) {
T tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
Exercise 2. Write a method that counts the elements of any list, whatever its type.
Show answer
static int count(List<?> list) {
int n = 0;
for (Object o : list) n++;
return n;
}
Frequently Asked Questions
What is the diamond operator?
The empty angle brackets in new ArrayList<>(). Since Java 7 the compiler infers the type arguments from the variable’s declared type.
Do generics slow programs down?
No. Thanks to erasure, generic code compiles to the same bytecode as code that uses casts, so there is no run-time cost.
Summary
- Generics move type errors from run time to compile time and remove casts.
- Declare type parameters on classes (
Box<T>) or methods (<T> T f()). - Bounds such as
T extends Comparable<T>unlock methods on T. - Wildcards make APIs flexible: producer extends, consumer super.
Next: Java Enums and Records.
