2011-09-01

Generics in Java — a summary for beginners

class Container<T> {

    private T type;

    void add(T type) {
        this.type = type;
    }

    T get() {
        return this.type;
    }
}
T is a Generic, aka formal type parameter aka type variable. Generics are also applicable to interfaces. They are used to reduce the scope of the (in this case) t variable. Also you can spare explicit castings which you may need without using Generics. If you omit <T> in the class declaration, you could put any Object in place of t. But so the class would be too specific. On the other hand if you don't specify the exact type of t and use Object instead of T, the code might throw Exceptions at runtime. So you can't catch syntactical error at compile time. Generic type invocations are instations of classes that use Generics:

Container<Integer> containerOfInteger; // that's how you read it, but you may write "stringContainer"

As you see I'm using the Object Integer instead of the primitive type int. That's because formal type parameters have to be Objects — primitive types like short, int, and boolean are not allowed. Instead you can use their Object equivalents: Short, Integer, and Boolean.

During compilation all generic information is removed from a Java class which is called Type Erasure.