Skip to lesson

Write a generic class

A generic class declares one or more type parameters after its name, like class Box<T> or class Pair<K, V>. Inside the class, T stands for whatever type the user picks, and it works like any other type for fields, parameters and return types.

Declaring a generic class

A generic class is a class that declares one or more type parameters in angle brackets after its name, like class Box<T>. Each use fills them in, so one class gives Box<String>, Box<Integer> and more. Generic classes and generic interfaces are together called generic types.

An online store needs small holders for many values: a product name, a price, the deal of the day. Write the class once with <T> after its name, then use T for the field, the constructor and the methods.

One generic class, many types. class Box<T> with a field T item, T get() and void set(T item) is written once. It is used as Box<String> holding "Laptop", Box<Integer> holding 60000 and Box<Product> holding a Monitor product for Rs. 11000.

Example 1 · A generic Box with a constructor

BoxDemo.javaJava
class Product {    String name;    int price;
    Product(String name, int price) {        this.name = name;        this.price = price;    }}
class Box<T> {    private T item;
    Box(T item) {        this.item = item;    }
    T get() {        return item;    }
    void set(T item) {        this.item = item;    }
    boolean isEmpty() {        return item == null;    }}
public class BoxDemo {    public static void main(String[] args) {        Box<String> product = new Box<>("Laptop");        Box<Integer> price = new Box<>(60000);        Box<Product> deal = new Box<>(new Product("Monitor", 11000));
        System.out.println(product.get() + " costs Rs. " + price.get());        System.out.println("Deal: " + deal.get().name + ", Rs. " + deal.get().price);
        product.set(null);        System.out.println("Product box empty? " + product.isEmpty());    }}
Output
Laptop costs Rs. 60000
Deal: Monitor, Rs. 11000
Product box empty? true

What this code does

  • class Box<T> declares T once; the field, the constructor parameter and the methods then use it like a normal type.
  • The constructor is written Box(T item), without <T>. In new Box<>("Laptop"), the Java compiler (javac) takes String from the left side.
  • isEmpty() compares with null, which works for every T, because every type argument is an object type.

A common slip is writing Box<T>(T item) for the constructor. The class has already declared T, so the constructor is just Box(T item); the <> belongs only after the class name and after new.

Two type parameters, and how to name them

Type parameter names are, by convention, single capital letters: T for type, E for element, K for key, V for value and N for number. A single letter shows at a glance that it is a placeholder, not a real class like String.

A bundle pairs two values of different types: a bundle name and its price, or an order number and the customer. List the type parameters with commas: class Pair<K, V>.

Example 2 · Pair<K, V> with two type parameters

PairDemo.javaJava
class Pair<K, V> {    private K first;    private V second;
    Pair(K first, V second) {        this.first = first;        this.second = second;    }
    K getFirst() {        return first;    }
    V getSecond() {        return second;    }}
public class PairDemo {    public static void main(String[] args) {        Pair<String, Integer> bundle = new Pair<>("Headphones + USB hub", 9500);        Pair<Integer, String> ticket = new Pair<>(17, "Priya");        Pair<String, Boolean> stock = new Pair<>("Charger", false);
        System.out.println(bundle.getFirst() + ": Rs. " + bundle.getSecond());        System.out.println("Ticket " + ticket.getFirst() + " is for " + ticket.getSecond());        System.out.println(stock.getFirst() + " in stock? " + stock.getSecond());    }}
Output
Headphones + USB hub: Rs. 9500
Ticket 17 is for Priya
Charger in stock? false

What this code does

  • Pair<K, V> has two independent type parameters. Pair<String, Integer> fills K with String and V with Integer; Pair<Integer, String> swaps them.
  • Each getter returns its own type, so bundle.getSecond() is an Integer and ticket.getSecond() is a String, with no casts.

Java's own HashMap<K, V>, in HashMap basics (opens in a new tab), uses exactly these names: a key of type K leads to a value of type V. Any valid name compiles, even <Item>, but then readers mistake it for a real class.

Generic interfaces

A generic interface is an interface with a type parameter, like interface Source<T>. A class that implements it either fixes the type (implements Source<Integer>) or stays generic itself (class Repeater<T> implements Source<T>).

An interface can take a type parameter too. Source<T> promises one method, T next(), that hands out the next value. Each class that implements it, as in Interfaces (opens in a new tab), chooses what T is.

Example 3 · One generic interface, two implementations

SourceDemo.javaJava
interface Source<T> {    T next();}
class TicketMachine implements Source<Integer> {    private int last = 100;
    public Integer next() {        last++;        return last;    }}
class DealBoard implements Source<String> {    private String[] products = { "Smartwatch", "Wireless charger", "Power bank" };    private int day = 0;
    public String next() {        String product = products[day % products.length];        day++;        return product;    }}
public class SourceDemo {    public static void main(String[] args) {        Source<Integer> tickets = new TicketMachine();        Source<String> board = new DealBoard();
        System.out.println("Ticket " + tickets.next() + ", ticket " + tickets.next());        for (int i = 1; i <= 4; i++) {            System.out.println("Day " + i + ": " + board.next());        }    }}
Output
Ticket 101, ticket 102
Day 1: Smartwatch
Day 2: Wireless charger
Day 3: Power bank
Day 4: Smartwatch

What this code does

  • implements Source<Integer> fixes T to Integer, so TicketMachine must write public Integer next(). DealBoard fixes it to String.
  • Source<Integer> tickets = new TicketMachine(); uses the interface as a type, and the Java compiler knows tickets.next() returns an Integer.
  • Interface methods are public, so the implementing methods must be public too.

Java's own Comparable<T>, used in Bounded types (opens in a new tab), is a generic interface of exactly this kind.

Type arguments must be objects: wrappers and autoboxing

Autoboxing is Java's automatic conversion of a primitive value into its wrapper object, such as int to Integer; unboxing is the reverse. It lets you write price.set(60000) and int p = price.get(); with a Box<Integer>.

A type argument must be a class type, so Box<int> does not compile. Each primitive has a wrapper class, an object form of it: Integer for int, Double for double, Character for char, Boolean for boolean.

Example 4 · Box<int> does not compile

PrimitiveDemo.javaJava
class Box<T> {    private T value;
    void set(T value) {        this.value = value;    }
    T get() {        return value;    }}
public class PrimitiveDemo {    public static void main(String[] args) {        Box<int> price = new Box<>();        price.set(60000);        System.out.println(price.get());    }}
Sample compiler output
PrimitiveDemo.java:15: error: unexpected type
        Box<int> price = new Box<>();
            ^
  required: reference
  found:    int
1 error

What this code does

  • "unexpected type ... required: reference, found: int": a type argument must be a reference (object) type, and int is a primitive.
  • The fix is the wrapper class: Box<Integer> price = new Box<>();. The other two lines stay the same.

Example 5 · Autoboxing and unboxing at work

AutoboxDemo.javaJava
class Box<T> {    private T value;
    void set(T value) {        this.value = value;    }
    T get() {        return value;    }}
public class AutoboxDemo {    public static void main(String[] args) {        Box<Integer> headphones = new Box<>();        Box<Integer> hub = new Box<>();        headphones.set(6000);        hub.set(3500);
        int bill = headphones.get() + hub.get();        System.out.println("Bill: Rs. " + bill);
        Box<Double> rating = new Box<>();        rating.set(4.5);        double stars = rating.get();        System.out.println("Rating: " + stars + " stars");
        Box<Character> grade = new Box<>();        grade.set('A');        System.out.println("Seller grade: " + grade.get());    }}
Output
Bill: Rs. 9500
Rating: 4.5 stars
Seller grade: A

What this code does

  • headphones.set(6000) autoboxes: the Java compiler turns the int 6000 into an Integer object for you.
  • headphones.get() + hub.get() unboxes both Integer objects back to int values, adds them and stores 9500 in bill.
  • The same works for every pair: 4.5 becomes a Double, 'A' a Character.

The eight pairs are byte/Byte, short/Short, int/Integer, long/Long, float/Float, double/Double, char/Character and boolean/Boolean. Only Integer and Character are not just the primitive name with a capital letter.

Two traps with wrapper types

The Integer cache is a set of ready-made Integer objects for the values -128 to 127 that Java reuses when it autoboxes. That is why == on two boxed numbers is true for small values and usually false for bigger ones.

A wrapper is an object, so it can be null, and == on it compares references, as in == compares references (opens in a new tab). Both traps compile without a warning.

Example 6 · Unboxing null crashes

NullUnboxDemo.javaJava
class Box<T> {    private T value;
    void set(T value) {        this.value = value;    }
    T get() {        return value;    }}
public class NullUnboxDemo {    public static void main(String[] args) {        Box<Integer> discount = new Box<>();        System.out.println("Discount set? " + (discount.get() != null));        int off = discount.get();        System.out.println("You save Rs. " + off);    }}
Sample output (the program stops with an exception)
Discount set? false
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "Box.get()" is null
	at NullUnboxDemo.main(NullUnboxDemo.java:17)

What this code does

  • The box was never filled, so get() returns null.
  • int off = discount.get(); must unbox, which calls intValue() on null: a NullPointerException, and the message says so.
  • Fix: Integer d = discount.get(); int off = (d == null) ? 0 : d;.

The rules: compare wrapper values with equals, never with ==; and before unboxing a wrapper that may be empty, check it for null, or keep it as Integer until you know a value is set.

Predict the output

Integer: == or equals?

Read each program and pick what it prints.

Round 1 of 4

Two tickets with the number 100.

public class CacheSmall {
public static void main(String[] args) {
Integer a = 100;
Integer b = 100;
System.out.println(a == b);
}
}

Next step

Check your understanding

12 quick questions