Skip to content

🔤 Java Generics – Type-Safe Collections and Methods

🔖 Introduction

Imagine writing a method that works for any data type—without rewriting it for each one. That’s the power of Generics in Java.

Generics make your code:

  • Reusable
  • Type-safe
  • Cleaner and more readable

Let’s see how 🚀

💡 What Are Generics?

Generics allow you to define classes, interfaces, and methods with type parameters (like T, E, K, V) instead of using specific data types.

List<String> names = new ArrayList<>();

Here, List<String> is a generic type where String is the type parameter.


📋 Why Use Generics?

✅ Benefits:

  • Catch type errors at compile time
  • Avoid type casting
  • Write reusable code

🧺 Generic Collections – A Better Way

Instead of this:

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

Use this:

List<String> list = new ArrayList<>();
list.add("Hello");
String name = list.get(0);  // No cast needed

🔧 Custom Generic Class Example

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(123);
System.out.println(intBox.get());  // 123

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

🔁 Generic Method Example

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

Usage:

String[] names = {"Alice", "Bob"};
Utils.printArray(names);

Integer[] numbers = {1, 2, 3};
Utils.printArray(numbers);

📌 Common Type Parameters

SymbolMeaning
TType
EElement (collections)
KKey
VValue

🔒 Bounded Type Parameters

Want to restrict the types? Use extends:

public class Calculator<T extends Number> {
    public double square(T number) {
        return number.doubleValue() * number.doubleValue();
    }
}

Usage:

Calculator<Integer> calc = new Calculator<>();
System.out.println(calc.square(5));  // 25.0

❗ Generics and Primitives

Java Generics don’t work with primitives like int or double.

But thanks to autoboxing, you can use their wrappers:

List<Integer> numbers = new ArrayList<>();

🧪 Mini Challenge

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

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

    public void printPair() {
        System.out.println(key + " = " + value);
    }
}

public class Main {
    public static void main(String[] args) {
        Pair<String, Integer> age = new Pair<>("Alice", 30);
        age.printPair();  // Alice = 30
    }
}

✅ What You Learned

  • What generics are and why they matter
  • How to create generic classes and methods
  • The benefits of compile-time type checking
  • Bounded types and common conventions

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *