🧩 Generics in Java – Type-Safe Code Simplified

What are Generics?

Generics in Java allow you to write type-safe and reusable code by enabling classes, interfaces, and methods to operate on objects of various types while providing compile-time type checking.


🔍 Why Use Generics?

Without generics:

List list = new ArrayList();
list.add("Hello");
String s = (String) list.get(0); // Unsafe cast

With generics:

List<String> list = new ArrayList<>();
list.add("Hello");
String s = list.get(0); // No casting needed – type-safe

Benefits:

  • Compile-time type checking
  • No need for casting
  • Code reusability
  • Reduced runtime errors

🏗️ Generic Class Example

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

Usage:

Box<Integer> intBox = new Box<>();
intBox.set(100);
System.out.println(intBox.get());  // Output: 100

Box<String> strBox = new Box<>();
strBox.set("Java");
System.out.println(strBox.get());  // Output: Java

 


⚙️ Generic Method Example

public class Utility {
    public static <T> void printArray(T[] array) {
        for (T item : array)
            System.out.print(item + " ");
    }
}

Usage:

String[] names = {"Alice", "Bob"};
Utility.printArray(names); // Output: Alice Bob

🔐 Bounded Types

Limit generic types to a specific class hierarchy:

public class NumberBox<T extends Number> {
    private T num;
    public void set(T num) { this.num = num; }
    public T get() { return num; }
}

🌀 Wildcards in Generics

Wildcard Use Case
<?> Unknown type
<? extends T> Accepts T or its subclasses
<? super T> Accepts T or its superclasses

Example:

public void printList(List<?> list) {
    for (Object obj : list) {
        System.out.println(obj);
    }
}
 

🧠 Summary

Generics help write robust, reusable, and type-safe code. They're widely used in Java Collections (like List<E>, Map<K,V>, etc.) and custom data structures.

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.