Generic Programming in Java

Generic programming helps you write flexible and reusable code.

In Java, we use Generics to write classes and methods that work with different types.


Why Use Generics?

Imagine a box.

Sometimes you want to put apples inside.

Other times, you want to put books.

You don't want to create a new box class each time.

You want one box class that works with any item.

This is where Generics help.


A Simple Box Example

Let’s write a class that holds any object:


public class Box<T> {
    private T item;

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

    public T getItem() {
        return item;
    }
}
  

<T> means this class can hold any type T.

You decide what T is when you create the object.

Using the Box:


Box<String> stringBox = new Box<>();
stringBox.setItem("Hello");
System.out.println(stringBox.getItem()); // prints Hello

Box<Integer> intBox = new Box<>();
intBox.setItem(42);
System.out.println(intBox.getItem()); // prints 42
  

One class, many types. That’s the power of Generics.


Benefits of Generics


Real-Life Example: Shopping Bag

Imagine a shopping bag that can carry different things.


public class ShoppingBag<T> {
    private List<T> items = new ArrayList<>();

    public void addItem(T item) {
        items.add(item);
    }

    public T getItem(int index) {
        return items.get(index);
    }
}
  

Now we can make a bag for fruits or clothes:


ShoppingBag<String> fruitBag = new ShoppingBag<>();
fruitBag.addItem("Apple");
fruitBag.addItem("Banana");

ShoppingBag<String> clothesBag = new ShoppingBag<>();
clothesBag.addItem("Shirt");
clothesBag.addItem("Pants");
  

Generic Methods

You can also create methods that use Generics.


public class Utils {
    public static <T> void printItem(T item) {
        System.out.println("Item: " + item);
    }
}
  

Usage:


Utils.printItem("Hello");
Utils.printItem(100);
Utils.printItem(3.14);
  

Same method works for all types.


Wildcards: <?>

Sometimes, you don’t care about the exact type.

You just want to say "any type".


public void printBag(ShoppingBag<?> bag) {
    System.out.println(bag.getItem(0));
}
  

The ? means "unknown type".


Generics with Java Collections

Generics are used a lot with lists, maps, and other collections.


List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");

Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 90);
scores.put("Bob", 85);
  

Without Generics, you'd write more code and get more errors.


Conclusion

Generics make your code cleaner and safer.

You write code once and use it many times with different types.

It’s like writing one recipe that works for any ingredient.

Now you are ready to write type-safe and reusable Java code!