Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Exceptions and Generics

    Generic Classes and Methods

    A generic class declares type parameters in angle brackets: class Box<T>. T is a placeholder filled in when the class is used.

    Chapter 7 of 103 min read

    The Plain Picture#

    One blueprint for a box, with a blank on the label: "Box of ____". When you order one, you fill in the blank: box of shoes, box of books. Same blueprint, checked contents.

    The Real Names#

    • A generic class declares type parameters in angle brackets: class Box<T>. T is a placeholder filled in when the class is used.

    • Conventional names: T type, E element, K key, V value, R result, A, B for several.

    • The diamond operator <> lets Java infer the type from the left side: Box<String> b = new Box<>("Priya");

    • A generic method declares its own type parameter before the return type: static <T> T first(List<T> items).

    • Type arguments must be object types — Box<Integer>, never Box<int> (Ch 9 explains why; wrappers are from Classes, Objects and Memory Ch 8).

    Under the Hood#

    Java
    class Box<T> {
        private T value;
    
        Box(T value) {
            this.value = value;
        }
    
        T get() {
            return value;
        }
    }
    
    record Pair<A, B>(A first, B second) {} // records can be generic too (03_java_oop.md Ch 12)
    
    Box<String> b = new Box<>("Priya");
    
    String name = b.get(); // no cast
    
    Pair<String, Integer> p = new Pair<>("Priya", 200);
    
    System.out.println(name + " " + p); // Priya Pair[first=Priya, second=200]

    Types you'll write constantly in DSA (collections in Collections, From the Inside):

    Java
    List<Integer>                  a growable list of numbers
    Map<String, Integer>           word → count
    Map<Integer, List<Integer>>    node → its neighbours (a graph)
    Set<List<Integer>>             unique triplets (e.g. the "3Sum" problem)
    PriorityQueue<int[]>           a heap of [distance, node] pairs (arrays are objects, so int[] is allowed)

    Check yourself

    3 questions
    1

    What does the T in class Box<T> mean?

    Show answer

    A type parameter: a placeholder for whatever type is supplied when the class is used.

    2

    What does <> do in new Box<>("x")?

    Show answer

    Lets the compiler infer the type argument from context.

    3

    Why is List<int> illegal but List<int[]> legal?

    Show answer

    Type arguments must be reference (object) types; int is a primitive, but int[] is an array — an object.