Generics in Java

🔹 What are Generics in Java?

Generics allow you to write classes, interfaces, and methods where the type of data is specified as a parameter.
This makes your code type-safe, reusable, and easier to read.

Instead of writing separate classes/methods for different data types, you can use type parameters (<T>, <E>, <K, V>, etc.).


🔹 Example 1: Generic Class

// A generic class with type parameter T
class Box<T> {
    private T value;

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

    public T getValue() {
        return value;
    }
}

public class GenericExample {
    public static void main(String[] args) {
        // Box for Integer
        Box<Integer> intBox = new Box<>();
        intBox.setValue(100);
        System.out.println("Integer Value: " + intBox.getValue());

        // Box for String
        Box<String> strBox = new Box<>();
        strBox.setValue("Hello Generics");
        System.out.println("String Value: " + strBox.getValue());
    }
}

✅ Output:

Integer Value: 100
String Value: Hello Generics

🔹 Example 2: Generic Method

class Util {
    // A generic method
    public static <T> void printArray(T[] array) {
        for (T element : array) {
            System.out.print(element + " ");
        }
        System.out.println();
    }
}

public class GenericMethodExample {
    public static void main(String[] args) {
        Integer[] intArr = {1, 2, 3, 4};
        String[] strArr = {"A", "B", "C"};

        Util.printArray(intArr);  // works with Integer array
        Util.printArray(strArr);  // works with String array
    }
}

✅ Output:

1 2 3 4 
A B C 

🔹 Example 3: Generic with Multiple Types (<K, V>)

class Pair<K, V> {
    private K key;
    private V value;

    public Pair(K key, V value) {
        this.key = key;
        this.value = value;
    }

    public void print() {
        System.out.println("Key: " + key + ", Value: " + value);
    }
}

public class MultiTypeGenerics {
    public static void main(String[] args) {
        Pair<Integer, String> pair1 = new Pair<>(1, "One");
        Pair<String, String> pair2 = new Pair<>("Name", "Alice");

        pair1.print();
        pair2.print();
    }
}

✅ Output:

Key: 1, Value: One
Key: Name, Value: Alice

🔑 Why use Generics?

  • Ensures compile-time type safety (no ClassCastException at runtime).
  • Eliminates the need for casting.
  • Improves code reusability.

Leave a Reply