Skip to content
Tutorials Center
My learning

Topics

Lesson 95 of 201 ยท Generics and Functional Programming

Generics

Learn Java generics - why they exist, writing generic classes, interfaces and methods, type inference and the diamond operator, invariance, and why raw types are unsafe.

Every collection you've used so far had angle brackets: List<String>, Map<String, Integer>, Deque<Task>. Those brackets are generics, the feature that lets one class work with many types while the compiler still knows exactly which type each object holds. Thanks to generics, names.get(0) returns a String you can use immediately, and names.add(42) is rejected before the program ever runs.

Generics arrived in Java 5 (2004). Before that, collections stored plain Object references: you could put anything in, and you had to cast everything you took out, hoping you guessed right. This lesson shows the problem generics solve, then teaches you to write your own generic classes, interfaces and methods, explains type inference and the diamond operator, and covers two rules that surprise everyone at first: List<Integer> is not a List<Number>, and raw types switch the safety off.

The problem: collections of Object

Here's what Java code looked like before generics. A raw List holds Object, so the compiler can't stop you from mixing types, and every read needs a cast:

Java A raw list fails at runtime, a generic list at compile time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The generic version prints its total. The raw version compiles, then crashes with a ClassCastException far from the line that caused the problem: the bad add happened earlier, maybe in a different class written by a different person. Generics move the mistake to compile time, where it's reported on the exact line, and they remove the casts. That's the whole point: type safety without casts.

Writing a generic class

A generic class declares one or more type parameters in angle brackets after its name. Inside the class, the parameter is used like a normal type:

Java
public class Box<T> {
    private T content;

    public Box(T content) { this.content = content; }
    public T get() { return content; }
    public void set(T content) { this.content = content; }
}

When you use the class, you supply a type argument: Box<String>, Box<LocalDate>, Box<List<Integer>>. The compiler then treats every T in that object as the type you chose.

By convention, type parameters are single uppercase letters, so they never look like class names:

Name Usually means
T a type (the first one)
U, S a second and third type
E an element of a collection
K, V the key and value of a map
R a result type
N a number

Records can be generic too, which makes small typed containers a one-liner:

Java A generic class and a generic record

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Box<String> and Box<LocalDate> are the same class, compiled once, but the compiler checks each use separately. Pair<A, B> shows two type parameters, and its withSecond method introduces a third, C, of its own: that's a generic method, covered next.

Generic methods

A method can declare its own type parameters, written before the return type. This is how utility methods like List.of, Collections.max and Arrays.asList work with any type:

Java
static <T> T firstOrDefault(List<T> items, T fallback) { ... }
//     ^^^ declares T for this method only

The caller usually doesn't write the type argument. The compiler infers it from the arguments and from where the result goes:

Java Generic methods and type inference

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In firstOrDefault(List.of(), -1) the empty list gives no clue, so the compiler uses the other argument and the target variable to infer Integer. When inference can't work it out, you can name the type explicitly with a type witness, Main.<String>repeat(...), but you'll rarely need it.

Generic methods can be static or instance methods, and they can live in non-generic classes. Use one whenever a method's parameter types and return type are connected: "returns the same type it received" is exactly what <T> expresses.

The diamond operator

Before Java 7 you had to repeat the type arguments on both sides:

Java
Map<String, List<Integer>> scores = new HashMap<String, List<Integer>>();

The diamond <> tells the compiler to infer them from the declaration:

Java
Map<String, List<Integer>> scores = new HashMap<>();

The diamond works wherever the compiler can see a target type: variable declarations, return statements and method arguments. Since Java 9 it also works with anonymous classes. Combined with var, put the types on the right instead, because var list = new ArrayList<>(); infers ArrayList<Object>, which is rarely what you want:

Java
var scores = new HashMap<String, List<Integer>>();   // good: types are explicit
var oops = new ArrayList<>();                        // ArrayList<Object>

Generic interfaces

Interfaces can be generic in the same way, and you've already implemented one: Comparable<T>. A class picks the type argument when it implements the interface, or stays generic and passes its own parameter along:

Java
interface Repository<T, ID> {
    void save(T item);
    Optional<T> findById(ID id);
    List<T> findAll();
}

class InMemoryRepository<T, ID> implements Repository<T, ID> { ... }   // stays generic
class UserRepository implements Repository<User, Long> { ... }         // fixes the types

This pattern is everywhere in real applications (Spring Data repositories look almost exactly like this; see Advanced Java). It lets you write the storage logic once and reuse it for every entity type.

Subtyping: List of Integer is not a List of Number

Integer is a subtype of Number, so you might expect List<Integer> to be a subtype of List<Number>. It isn't. Generic types are invariant: List<Integer> and List<Number> are unrelated types. The compiler forbids the assignment because it would open a hole:

Java
List<Integer> ints = new ArrayList<>(List.of(1, 2, 3));
List<Number> nums = ints;        // compile error: incompatible types
nums.add(2.5);                   // ...otherwise this would put a Double into ints
int x = ints.get(3);             // ...and this would crash

Arrays made the opposite choice long ago: they are covariant, so Integer[] is an Object[]. The price is a runtime check on every array store:

Java Covariant arrays need a runtime check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Generics catch the problem at compile time instead. When you do want a method that accepts "a list of any kind of number", you use a wildcard such as List<? extends Number>, as the last line shows. That's the topic of the next lesson, Bounded Types and Wildcards.

Raw types: the escape hatch to avoid

A raw type is a generic type used without type arguments: List instead of List<String>. Raw types exist only so that pre-2004 code still compiles. Using one turns off generic checking for that variable, and the compiler warns you:

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

With -Xlint:unchecked (or in any IDE), the warning points at the exact line. The danger is that a raw reference can smuggle a wrong element into a properly typed list, and the error surfaces much later, on a line with no visible cast:

Java
List<String> names = new ArrayList<>();
List raw = names;              // raw type: warning, but compiles
raw.add(42);                   // unchecked call: an Integer enters a List<String>
String s = names.get(0);       // ClassCastException here, far from the cause

This situation, a variable of a generic type pointing at an object with the wrong contents, is called heap pollution. Type Erasure and Generic Limitations explains why the JVM can't catch it at the add.

Treat every "unchecked" warning as a bug report. Don't write raw types in new code: if you don't know or care about the element type, use List<?> (a list of some type), which is safe because the compiler won't let you add to it.

Primitive types are not allowed

Type arguments must be reference types. List<int> and Map<String, double> don't compile; you write List<Integer> and Map<String, Double>, and autoboxing converts values for you (Wrapper Classes and Autoboxing). For heavy numeric work, boxing costs time and memory, which is why the JDK offers primitive alternatives such as IntStream and the IntFunction family covered in Functional Interfaces. Project Valhalla is working on removing this limitation in a future Java version, but today it applies.

A complete example: a generic stack

Putting the pieces together, here's a small type-safe stack built on an ArrayList, with a generic static factory method:

Java A reusable generic Stack class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The same class serves browser history (Stack<String>) and arithmetic (Stack<Integer>), and each instance accepts only its own type. The @SafeVarargs annotation on of promises the compiler that the method uses its generic varargs array safely; Type Erasure and Generic Limitations explains when that promise is true. (For real code, prefer ArrayDeque, as Legacy Collections explains; this class is for learning.)

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main benefit of List<String> over a raw List?

    Generics give compile-time type checking and remove casts. Memory use and thread safety are unchanged, and primitives are still not allowed.
  2. 2. Does this compile? List<Integer> ints = new ArrayList<>(); List<Number> nums = ints;

    List<Integer> is not a subtype of List<Number>. If it were, you could add a Double through nums and corrupt the list of integers.
  3. 3. Where is the type parameter declared in static <T> T pick(T a, T b)?

    A generic method declares its type parameters in angle brackets before the return type. The caller's arguments then let the compiler infer T.
  4. 4. What type does var items = new ArrayList<>(); give items?

    With var there is no target type, so the diamond infers Object. Write new ArrayList<String>() when using var.
  5. 5. What happens? Object[] arr = new String[2]; arr[0] = 7;

    Arrays are covariant, so the assignment compiles, but every array store is checked at runtime and an Integer can't go into a String[].

Summary

  • Generics let one class or method work with many types while the compiler checks every use; they replace casts and runtime ClassCastExceptions with compile errors.
  • Declare type parameters after a class or interface name (class Box<T>, record Pair<A, B>) or before a method's return type (static <T> T first(...)).
  • The compiler infers type arguments for generic methods and for the diamond <>; with var, put the type arguments on the right.
  • Generic types are invariant: List<Integer> is not a List<Number>. Arrays are covariant and check stores at runtime instead.
  • Raw types (List without <...>) disable checking and cause heap pollution; use List<?> when the element type doesn't matter.
  • Type arguments must be reference types, so use wrapper classes like Integer.

Next: Bounded Types and Wildcards, where you'll restrict type parameters with extends and write flexible APIs with ? extends and ? super.