Generics: Code for Any Type

What are the angle brackets?

In ArrayList<String>, the <String> is a type parameter. ArrayList was written once, with a placeholder type, and you fill in the real type when you use it. This is called generics.

Think of it like this: A lunch box can hold sandwiches, rice or fruit. The box is the same – you just label it with what's inside, so nobody tries to drink from the sandwich box.

Writing your own generic class

Use a letter like T (for Type) as the placeholder:

class Box<T> {
    private T item;

    Box(T item) {
        this.item = item;
    }

    T get() {
        return item;
    }
}

public class Main {
    public static void main(String[] args) {
        Box<String> words = new Box<>("hello");
        Box<Integer> number = new Box<>(42);
        System.out.println(words.get().toUpperCase());
        System.out.println(number.get() + 8);
    }
}

Output

HELLO
50

Java knows words.get() gives a String and number.get() gives an Integer, so it can catch mistakes for you:

class Box<T> {
    T item;
    Box(T item) { this.item = item; }
}

public class Main {
    public static void main(String[] args) {
        Box<String> b = new Box<>("hi");
        int n = b.item;
    }
}

Output (the program does not compile)

Main.java:9: error: incompatible types: String cannot be converted to int
        int n = b.item;
                 ^

More than one type, and generic methods

class Pair<K, V> {
    K first;
    V second;

    Pair(K first, V second) {
        this.first = first;
        this.second = second;
    }
}

public class Main {
    static <T> void printTwice(T value) {
        System.out.println(value + " " + value);
    }

    public static void main(String[] args) {
        Pair<String, Integer> p = new Pair<>("Asha", 91);
        System.out.println(p.first + " scored " + p.second);
        printTwice("hey");
        printTwice(7);
    }
}

Output

Asha scored 91
hey hey
7 7

Tip: Common letters: T = type, E = element, K = key, V = value.

HOME LABS COMMUNITY DASHBOARD