Back to Study Material Java

Generics in Java

Generics were introduced in Java 5 to enable type-safe programming by allowing classes, interfaces, and methods to operate on a variety of types while prov...

Generics in Java

Writing Type-Safe Code with Generics

Generics were introduced in Java 5 to enable type-safe programming by allowing classes, interfaces, and methods to operate on a variety of types while providing compile-time type checking. Before generics, collections stored Object references, requiring explicit casting that could produce ClassCastException at runtime. Generics eliminate the need for casting and catch type mismatches early at compile time.

A generic class is declared with a type parameter in angle brackets. By convention, single uppercase letters are used: T for type, E for element, K for key, V for value. Here is a simple generic container:

class Box<T> { private T content; public void set(T content) { this.content = content; } public T get() { return content; } }

Box<String> stringBox = new Box<>(); stringBox.set("Hello"); String value = stringBox.get(); // no cast needed

Generic methods can have their own type parameters independent of the class:

public static <T extends Comparable<T>> T max(T a, T b) { return a.compareTo(b) >= 0 ? a : b; }

Bounded type parameters restrict which types are acceptable. T extends Comparable<T> means T must implement Comparable. Wildcards provide additional flexibility: List<?> accepts a list of any type, List<? extends Number> accepts lists of Number or its subclasses (upper bound), and List<? super Integer> accepts lists of Integer or its superclasses (lower bound).

Generics are implemented via type erasure in Java. The compiler checks types at compile time but removes type information at runtime, replacing type parameters with Object or the upper bound. This means you cannot create instances of type parameters (new T()) or check instanceof against them.

Interview tip: Interviewers often ask about the difference between List<?> and List<Object>. List<Object> only accepts a List<Object>, while List<?> accepts a list of any type. Also, you cannot add elements to a List<?> except null, while List<Object> allows adding any object.