Skip to main content
Advertisement

12.1 Generics

Generics is a Java feature that allows you to define a class or method where the data type it operates on is not fixed at the time of writing, but specified at the point of use. Introduced in Java 5, it is now an indispensable core syntax element in modern Java programming.

1. Why Do We Need Generics?

Without Generics, you would have to use Object (the supreme parent type of everything) to accommodate all possible data types. This forces you to perform manual type casting every time you retrieve a value ((String), (Integer), etc.), and if the cast is wrong, a ClassCastException explodes at runtime.

// Using Object without Generics (DANGEROUS!)
Object item = "Hello";
String s = (String) item; // Manual cast required
Integer n = (Integer) item; // Runtime Error! ClassCastException thrown

2. Creating a Generic Class

By convention, type parameters use single uppercase letters. (T = Type, E = Element, K = Key, V = Value)

// A generic Box class accepting a type parameter 'T'
public class Box<T> {
private T item; // Variable of type T

public void put(T item) {
this.item = item;
}

public T get() {
return item;
}
}

public class GenericExample {
public static void main(String[] args) {
// A box specifically for holding String
Box<String> strBox = new Box<>();
strBox.put("Hello, Generics!");
String result = strBox.get(); // Returns String directly — no casting needed!
System.out.println(result); // Hello, Generics!

// A box specifically for holding Integer
Box<Integer> intBox = new Box<>();
intBox.put(100);
int num = intBox.get();
System.out.println(num); // 100
}
}

3. Creating a Generic Method

Declare the type parameter before the return type in the method signature.

public class GenericUtil {
// A generic method that prints both values and returns the first one
public static <T> T printAndReturn(T first, T second) {
System.out.println("First: " + first);
System.out.println("Second: " + second);
return first;
}

public static void main(String[] args) {
String s = printAndReturn("Apple", "Banana");
Integer n = printAndReturn(10, 20);
}
}

4. Generics in Practice: The Collections API

The angle brackets (<>) you've already seen in ArrayList<String> and HashMap<String, Integer> are precisely Generics in action. The entire Java standard Collections API is built with Generics, guaranteeing Type Safety at compile time.

import java.util.ArrayList;

ArrayList<String> list = new ArrayList<>();
list.add("Java");
// list.add(123); // Compile Error! Only Strings are allowed.

Generics is an extremely powerful feature that simultaneously boosts both code reusability and type safety.

Advertisement