DEV Community

Sudhakar V
Sudhakar V

Posted on

Genrics in Java

In Java, Generics provide a way to create classes, interfaces, and methods with type parameters. They allow you to write more general, type-safe, and reusable code.


๐Ÿ”น Why Use Generics?

Without generics:

  • You use Object, and casting is required.
  • Type safety is not enforced at compile time.

With generics:

  • Type safety: Errors are caught at compile time.
  • Code reusability: One class can work with many data types.
  • Eliminates casting: The compiler automatically knows the type.

๐Ÿ”น Basic Generic Class Example

class Box<T> {
    private T value;

    public void set(T value) {
        this.value = value;
    }

    public T get() {
        return value;
    }
}
Enter fullscreen mode Exit fullscreen mode

Usage:

public class GenericTest {
    public static void main(String[] args) {
        Box<Integer> intBox = new Box<>();
        intBox.set(123);
        System.out.println(intBox.get());

        Box<String> strBox = new Box<>();
        strBox.set("Hello");
        System.out.println(strBox.get());
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น Generic Method Example

public class GenericMethodExample {
    public static <T> void printArray(T[] array) {
        for (T item : array) {
            System.out.println(item);
        }
    }

    public static void main(String[] args) {
        Integer[] intArray = {1, 2, 3};
        String[] strArray = {"A", "B", "C"};

        printArray(intArray);
        printArray(strArray);
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น Generic Interface Example

interface Printer<T> {
    void print(T item);
}

class StringPrinter implements Printer<String> {
    public void print(String item) {
        System.out.println("Printing: " + item);
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น Bounded Type Parameters

You can restrict a type parameter to a certain class or interface using extends.

class NumberBox<T extends Number> {
    private T number;

    public NumberBox(T number) {
        this.number = number;
    }

    public double getDoubleValue() {
        return number.doubleValue();
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น Wildcards in Generics

Wildcard Meaning
<?> Unbounded wildcard (any type)
<? extends T> Upper bound (T or subtype)
<? super T> Lower bound (T or supertype)

Example:

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

๐Ÿ”น Generics with Collections

List<String> names = new ArrayList<>();
names.add("Alice"); // Type safe
// names.add(123);   // Compile-time error
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น Type Erasure

At runtime, all generic type information is erased. This means:

  • List<String> and List<Integer> become just List.
  • You cannot use primitives (like int) directly โ€” use Integer, Double, etc.

๐Ÿ”น Summary

Feature Benefit
class<T> Generic class
<T> methodName() Generic method
interface<T> Generic interface
T extends Class Bounded type
<?>, <? extends>, <? super> Wildcards

Would you like examples using generics in real-world scenarios like a repository class, a utility class, or a comparator?

Top comments (0)