Skip to content

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

    Java / Exceptions and Generics

    Why Generics Exist

    A warehouse with unlabelled boxes. Anyone can put anything in any box. When you open the box you expected to contain shoes, you find a

    Chapter 6 of 102 min read

    The Plain Picture#

    A warehouse with unlabelled boxes. Anyone can put anything in any box. When you open the box you expected to contain shoes, you find a fish — and you only find out when you try to wear it.

    Labelled boxes — "SHOES ONLY" — are checked at the door: the fish is turned away before it gets in.

    The Real Names#

    Before Java 5 (2004), collections held plain Objects. That style still compiles — it's called a raw type — and shows the problem:

    Java
    List raw = new ArrayList();
    
    raw.add("Priya");
    
    raw.add(200); // compiles fine — nothing stops a number going into a "list of names"
    
    for (Object o : raw) {
        String s = (String) o; // you must cast when reading...
    }
    // raw list: ClassCastException at runtime     ← ...and it fails only when the program RUNS

    The compiler even warns you:

    Output
    warning: [unchecked] unchecked call to add(E) as a member of the raw type List

    Generics let you put a type parameter on a class or method — the label on the box:

    Java
    List<String> names = new ArrayList<>();
    
    names.add("Priya");
    
    names.add(200); // compile error — rejected at the door
    
    String first = names.get(0); // no cast needed

    Two gains: errors move from run time to compile time, and casts disappear. (Never use raw types in new code.)

    Check yourself

    2 questions
    1

    What is a raw type, and why is it dangerous?

    Show answer

    A generic type used without its type parameter (List instead of List<String>); it accepts anything, so type mistakes appear only at run time as ClassCastExceptions.

    2

    Name the two main benefits of generics.

    Show answer

    Type errors are caught at compile time; no casts when reading values.