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:
Tfor Type,Efor Element (used in Collections),KandVfor Key and Value. - Wildcards: Research
<? extends Number>for when you want a box that can hold any type of number.
Practice Exercises
- The Multi-Box: Create a generic class
Pair<K, V>that can store two different types of objects at once. - Generic Method: Write a method
printArray(T[] array)that can print any type of array (Strings, Integers, etc.). - The Brick Test: Try to create a
List<Object>and add a String and an Integer to it. Now try to do it withList<String>. What happens to your code at compile time?