JAVA-201 · Lesson 1 of 12 · 23 min
Generics and type parameters
▶ Video coming soon A video version of this lesson is on the way.
Hamza Belcourt's winter term has two Java courses side by side. On Wednesdays Ingrid Vallancourt takes him through object-oriented design, and the booking system ShopBook is the goal for April. This course is the other half of the term: the data structures that every real program leans on. Ingrid works from home on Fridays, so the plan is to meet in the parts room at Second Gear Cycles on Friday afternoons, from 2:00 to 4:00 pm, starting Friday, January 15, 2027. Kofi Amankwah, the parts lead, has agreed to lend the real parts list, about 600 kinds of parts, as practice data.
PartsDesk, Hamza's console inventory tool from JAVA-101, stored its parts in parallel arrays: one array of names, one of counts, one of shelf locations. That worked for 40 parts. For 600 parts, for lookups by code, for a list sorted by how close each part is to running out, and for the repair queue Tamsin Rhee wants, the shop needs proper containers. Java's are called collections, and every one of them is built on the feature this first lesson covers: generics.
The problem generics solve
A container has to hold something. Before Java 5, the standard containers held values of type Object, so they could hold anything, and the programmer had to remember what was really inside and cast it back out. A mistake compiled happily and failed later, at run time, often far from where the wrong value went in. Generics move that check to compile time. A generic class has a type parameter, written in angle brackets, which is filled in with a real type each time the class is used.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> parts = new ArrayList<>();
parts.add("700x25c inner tube");
parts.add("brake pads, road");
parts.add("chain, 11-speed");
String first = parts.get(0);
System.out.println("First part: " + first);
System.out.println("Parts listed: " + parts.size());
for (String p : parts) {
System.out.println("- " + p.toUpperCase());
}
}
}First part: 700x25c inner tube Parts listed: 3 - 700X25C INNER TUBE - BRAKE PADS, ROAD - CHAIN, 11-SPEED
What this code does
List<String> is a list whose elements are all Strings, so get(0) returns a String with no cast, and toUpperCase can be called on each element directly. The empty angle brackets after ArrayList are the diamond, which lets Java work out the type from the declaration. Trying to add a number to this list would be a compile error rather than a surprise later.
Read List<String> as "list of String". The type in the brackets is a type argument. The declaration says what the list holds, and from then on the compiler checks every add and inserts the right type for every get. The diamond <> on the right-hand side means "the same type arguments as the variable", so you do not have to write ArrayList<String> twice.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> counts = new ArrayList<>();
counts.add(14);
counts.add("twelve");
System.out.println(counts);
}
}What this code does
The list is declared to hold Integer values, so adding the String twelve is rejected when the program is compiled. javac reports incompatible types: a String cannot be converted to an Integer. The bug is found before the program ever runs, which is the whole point of generics.
$ javac Main.java
Main.java:8: error: incompatible types: String cannot be converted to Integer
counts.add("twelve");
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 errorWriting a generic class
You can write generic classes of your own. Kofi keeps each part in a numbered bin on a shelf, and a bin holds one kind of thing. A Bin<T> class can hold any type of item while still giving back exactly that type. Inside the class, T is used like an ordinary type name for fields, parameters and return types. By convention type parameters are single capital letters: T for a type, E for an element, K and V for keys and values.
public class Main {
public static void main(String[] args) {
Bin<String> b14 = new Bin<>("B-14");
b14.put("brake pads, road");
Bin<Integer> spokes = new Bin<>("S-02");
spokes.put(296);
String item = b14.take();
int length = spokes.take();
System.out.println(b14.label() + " held: " + item);
System.out.println(spokes.label() + " held spokes of length " + length + " mm");
System.out.println("B-14 empty now? " + b14.isEmpty());
}
}
class Bin<T> {
private final String label;
private T item;
Bin(String label) {
this.label = label;
}
void put(T item) {
if (this.item != null) throw new IllegalStateException(label + " is full");
this.item = item;
}
T take() {
T out = item;
item = null;
return out;
}
boolean isEmpty() { return item == null; }
String label() { return label; }
}B-14 held: brake pads, road S-02 held spokes of length 296 mm B-14 empty now? true
What this code does
Bin<T> is written once, and the same class holds a String in one bin and an Integer in another. take returns T, so the caller gets a String from b14 and an Integer from spokes without casting. The Integer is unboxed to an int automatically when it is stored in length.
Two details are worth noticing. First, type arguments must be reference types: you can write Bin<Integer> but not Bin<int>. Java converts between int and Integer automatically, which is called autoboxing and unboxing. Second, a class can have more than one type parameter. A Pair<A, B> holding two related values is a common example, and Map<K, V>, which you will meet in lesson 5, has two.
public class Main {
public static void main(String[] args) {
Pair<String, Integer> stock = new Pair<>("700x25c inner tube", 14);
Pair<String, String> shelf = new Pair<>("700x25c inner tube", "B-07");
System.out.println(stock.first() + " -> " + stock.second() + " in stock");
System.out.println(shelf.first() + " -> shelf " + shelf.second());
System.out.println(stock.swap());
}
}
record Pair<A, B>(A first, B second) {
Pair<B, A> swap() {
return new Pair<>(second, first);
}
@Override
public String toString() {
return "(" + first + ", " + second + ")";
}
}700x25c inner tube -> 14 in stock 700x25c inner tube -> shelf B-07 (14, 700x25c inner tube)
What this code does
Records can be generic too, so Pair<A, B> gets its constructor, accessors, equals and hashCode for free. The swap method returns a Pair with the type arguments the other way round. The same record holds a String and an Integer in one place and two Strings in another.
Generic methods
A method can have its own type parameter even when its class is not generic. The parameter list goes in angle brackets before the return type. Java usually infers the type argument from the arguments you pass, so you rarely write it out. Generic methods are how utility code such as Collections.max and List.of works for every element type.
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> shelves = List.of("B-07", "B-14", "C-03");
List<Integer> counts = List.of(14, 3, 22);
System.out.println("Last shelf: " + last(shelves));
System.out.println("Last count: " + last(counts));
System.out.println(repeat("tube", 3));
}
static <T> T last(List<T> items) {
if (items.isEmpty()) throw new IllegalArgumentException("empty list");
return items.get(items.size() - 1);
}
static <T> List<T> repeat(T value, int times) {
java.util.ArrayList<T> out = new java.util.ArrayList<>();
for (int i = 0; i < times; i++) out.add(value);
return out;
}
}Last shelf: C-03 Last count: 22 [tube, tube, tube]
What this code does
The <T> before the return type makes last and repeat generic methods. Called with a List<String>, last returns a String, and called with a List<Integer>, it returns an Integer, because Java infers T from the argument. repeat builds a list of whatever type it is given.
Bounded type parameters
Sometimes a generic method needs to do more with its values than store them. To find the largest of a list it must compare elements, and an arbitrary T has no compareTo method. A bounded type parameter restricts T to types that have what the method needs. <T extends Comparable<T>> means "any T that can be compared with another T". Inside the method you can then call compareTo, and the compiler refuses arguments whose type is not comparable.
import java.util.List;
public class Main {
public static void main(String[] args) {
System.out.println(largest(List.of(14, 3, 22, 9)));
System.out.println(largest(List.of("chain", "tube", "cable")));
System.out.println(total(List.of(14, 3, 22)));
System.out.println(total(List.of(2.5, 1.25)));
}
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;
}
static <N extends Number> double total(List<N> items) {
double sum = 0;
for (N n : items) sum += n.doubleValue();
return sum;
}
}22 tube 39.0 3.75
What this code does
largest only accepts element types that implement Comparable, so compareTo is guaranteed to exist, and it works for Integers and for Strings, which compare alphabetically. total is bounded by Number, so it can call doubleValue on Integers and Doubles alike. The bounds let each method use the abilities it needs while staying generic.
In a bound, extends is used for both classes and interfaces. You can combine bounds with an ampersand, as in <T extends Number & Comparable<T>>, where the class, if any, must come first. Lesson 7 returns to Comparable in detail.
Wildcards and the PECS rule
A surprising rule of generics is that a List<Integer> is not a List<Number>, even though an Integer is a Number. If it were, you could pass a List<Integer> to a method expecting List<Number>, and that method could legally add a Double to it, breaking the promise that the list holds only Integers. Generic types are therefore invariant. When a method should accept lists of several related types, you use a wildcard, written ?.
| Parameter type | Accepts | You may | Typical use |
|---|---|---|---|
| List<Number> | only List<Number> | read Number, add any Number | a list you own |
| List<? extends Number> | List<Number>, List<Integer>, List<Double> | read as Number; not add | a producer you read from |
| List<? super Integer> | List<Integer>, List<Number>, List<Object> | add Integers; read only as Object | a consumer you write into |
| List<?> | a list of anything | read as Object; not add | size, clear, printing |
The rule of thumb is PECS: *producer extends, consumer super*. If a parameter produces values for the method to read, declare it with ? extends T. If it consumes values that the method writes, declare it with ? super T. The standard library follows this rule throughout; Collections.copy, for example, takes a destination of type List<? super T> and a source of type List<? extends T>.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> tubes = List.of(14, 12, 9);
List<Double> grease = List.of(0.5, 0.75);
System.out.println("Tubes: " + sum(tubes));
System.out.println("Grease, litres: " + sum(grease));
List<Number> received = new ArrayList<>();
List<Object> log = new ArrayList<>();
addCounts(received, 3);
addCounts(log, 2);
System.out.println(received);
System.out.println(log);
}
static double sum(List<? extends Number> items) {
double s = 0;
for (Number n : items) s += n.doubleValue();
return s;
}
static void addCounts(List<? super Integer> into, int n) {
for (int i = 1; i <= n; i++) into.add(i * 10);
}
}Tubes: 35.0 Grease, liters: 1.25 [10, 20, 30] [10, 20]
What this code does
sum reads from its list, so it is a producer and uses ? extends Number, which lets it take lists of Integers and of Doubles. addCounts writes Integers into its list, so it is a consumer and uses ? super Integer, which lets it fill a List<Number> or a List<Object>. Neither method needs to know the exact element type of the list it is given.
Type erasure and its limits
Generics are a compile-time feature. After javac has checked the types, it removes most of the type arguments and inserts the casts you would otherwise have written by hand. This is called type erasure, and it was chosen so that generic code could run on the same Java virtual machine as older code. At run time, a List<String> and a List<Integer> are both just ArrayList objects.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
List<Integer> counts = new ArrayList<>();
System.out.println(names.getClass().getName());
System.out.println(counts.getClass().getName());
System.out.println("Same class at run time? " + (names.getClass() == counts.getClass()));
}
}java.util.ArrayList java.util.ArrayList Same class at run time? true
What this code does
Both lists report the class java.util.ArrayList, because the type arguments String and Integer were erased after compiling. The comparison of their classes prints true. The compiler did all the type checking, so the running program does not need to know the element types.
Erasure explains several things you cannot do with a type parameter T: you cannot write new T() or new T[10], because the type is not known at run time; you cannot test x instanceof List<String>; and you cannot overload two methods that differ only in their type arguments, such as print(List<String>) and print(List<Integer>). You may also see raw types, such as plain List with no brackets, in old code. They switch off generic checking and earn a compiler warning, so never use them in new code.
import java.util.List;
public class Main {
public static void main(String[] args) {
Object x = List.of("tube", "pads");
if (x instanceof List<String>) {
System.out.println("a list of strings");
}
}
}What this code does
The test instanceof List<String> cannot be checked at run time, because the element type has been erased. javac rejects it, saying Object cannot be safely cast to List<String>. You can test instanceof List<?> instead, which only asks whether the object is some kind of list.
$ javac Main.java
Main.java:6: error: Object cannot be safely cast to List<String>
if (x instanceof List<String>) {
^
1 errorTry it yourself
A generic Shelf
Complete the generic class Shelf<T>. Its add method stores an item in its ArrayList, count returns how many items it holds and first returns the first item added.
The program should print Pads shelf: 2 items, first is brake pads, road and then Spoke shelf: 3 items, first is 296.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
Shelf<String> pads = new Shelf<>();
pads.add("brake pads, road");
pads.add("brake pads, disc");
Shelf<Integer> spokes = new Shelf<>();
spokes.add(296);
spokes.add(298);
spokes.add(300);
System.out.println("Pads shelf: " + pads.count() + " items, first is " + pads.first());
System.out.println("Spoke shelf: " + spokes.count() + " items, first is " + spokes.first());
}
}
class Shelf<T> {
private final List<T> items = new ArrayList<>();
void add(T item) {
}
int count() {
return 0;
}
T first() {
return null;
}
}Try it yourself
A bounded smallest method
Write the generic method smallest, bounded so that its elements can be compared, which returns the smallest element of a list.
Kofi wants the lowest stock count and the alphabetically first shelf label. The program should print Lowest count: 3 and First shelf: A-11.
import java.util.List;
public class Main {
public static void main(String[] args) {
System.out.println("Lowest count: " + smallest(List.of(14, 3, 22, 9)));
System.out.println("First shelf: " + smallest(List.of("B-07", "C-03", "A-11")));
}
static <T extends Comparable<T>> T smallest(List<T> items) {
return items.get(0);
}
}Common mistakes
MistakeWriting List<int> or Bin<double>.
InsteadType arguments must be reference types: use List<Integer> and Bin<Double>; Java boxes and unboxes the values for you.
MistakeExpecting a List<Integer> to be accepted where a List<Number> is required.
InsteadGeneric types are invariant; declare the parameter as List<? extends Number> if the method only reads from it.
MistakeTrying to add to a List<? extends Number>.
InsteadA producer wildcard is read-only; use ? super T for a list the method writes into.
MistakeWriting new T[10] or new T() inside a generic class.
InsteadType arguments are erased at run time; use an ArrayList<T>, or pass in a factory or a Class object.
MistakeUsing raw types such as plain List in new code.
InsteadAlways give the type argument, even if it is only <?>, so the compiler can check your code.
Summary and key terms
- Generics let a class or method work with many types while the compiler checks that each use is consistent.
- A generic class declares type parameters in angle brackets, such as Bin<T> or Pair<A, B>, and each use fills them in with type arguments.
- Type arguments must be reference types, and autoboxing converts between int and Integer.
- The diamond <> lets Java infer type arguments in a constructor call.
- Generic methods put their type parameters before the return type, and Java usually infers them.
- Bounded type parameters such as <T extends Comparable<T>> let a method call methods of the bound.
- Generic types are invariant, so wildcards are used for flexibility: ? extends T for producers and ? super T for consumers, which is the PECS rule.
- Type arguments are erased after compiling, so you cannot create a new T, test instanceof List<String> or rely on element types at run time.
- Generic class
- A class with one or more type parameters, such as Bin<T>.
- Type parameter
- A placeholder for a type, such as T, E, K or V, declared in angle brackets.
- Type argument
- The actual type filled in when a generic type is used, such as String in List<String>.
- Diamond
- The empty angle brackets <> that let Java infer type arguments in a constructor call.
- Autoboxing
- Automatic conversion between a primitive such as int and its wrapper such as Integer.
- Generic method
- A method with its own type parameters, written before its return type.
- Bounded type parameter
- A type parameter limited to subtypes of a bound, as in <T extends Comparable<T>>.
- Invariance
- The rule that List<Integer> is not a subtype of List<Number>.
- Wildcard
- The ? in a type such as List<? extends Number>, standing for an unknown type.
- PECS
- Producer extends, consumer super: the rule for choosing wildcards.
- Type erasure
- The removal of type arguments after compiling, so they are not known at run time.
- Raw type
- A generic type used without type arguments, which turns off generic checking.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Why does List<Integer> counts; counts.add("twelve"); fail to compile?
Show answer
The list only accepts Integers, so adding a String is a type error found by the compiler.
What does the diamond in new ArrayList<>() do?
Show answer
It lets Java take the type arguments from the variable's declared type.
Why can't you write List<int>?
Show answer
Type arguments must be reference types; use List<Integer>.
A method only reads Numbers from a list. How should the parameter be declared?
Show answer
As List<? extends Number>, a producer.
Why can't a generic class create new T[10]?
Show answer
Type erasure means T is not known at run time.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.