Java Generics: The Labelled Container

Java Generics: The Labelled Container in Java: Imagine you have a Storage Box. Without Generics: You can throw anything inside — a shoe, a sandwich, or a…

Concept Explanation

Imagine you have a Storage Box.

  • Without Generics: You can throw anything inside — a shoe, a sandwich, or a brick. But when you reach in blindly (Object), you might grab the sandwich when you wanted the shoe, or get a face full of brick (ClassCastException).
  • With Generics: You put a label on the box that says "SHOES ONLY". Now, Java won't even let you put a sandwich inside, and you are 100% sure what you'll get when you open it.

Syntax or Core Structure

We use angle brackets <T> to represent a Type.

// Generic Class
class Box<T> {
    private T item;
    public void set(T item) { this.item = item; }
    public T get() { return item; }
}

// Usage
Box<String> stringBox = new Box<>();
stringBox.set("Hello");
// stringBox.set(123); // COMPILE ERROR! Safe!

Best Practices

  • Use Descriptive Letters: T for Type, E for Element (used in Collections), K and V for Key and Value.
  • Wildcards: Research <? extends Number> for when you want a box that can hold any type of number.

Practice Exercises

  1. The Multi-Box: Create a generic class Pair<K, V> that can store two different types of objects at once.
  2. Generic Method: Write a method printArray(T[] array) that can print any type of array (Strings, Integers, etc.).
  3. The Brick Test: Try to create a List<Object> and add a String and an Integer to it. Now try to do it with List<String>. What happens to your code at compile time?