Generics allow you to create classes, interfaces, and methods where the type of data it operates on is specified as a parameter.
Key Benefits
Type Safety: The computer checks at compile-time to make sure you aren't putting a "Banana" into a "Laptop" box.
No Casting: You don't need to write
(String)or(Integer)when pulling data out.Code Reuse: Write one class that works for any data type.
The Code Example:
// We use <T> as a placeholder for "Type"
class Box<T> {
private T contents;
public void add(T item) {
this.contents = item;
}
public T get() {
return contents;
}
}
public class GenericsDemo {
public static void main(String[] args) {
// 1. A Box for Strings
Box<String> messageBox = new Box<>();
messageBox.add("Secret Message");
// messageBox.add(123); // Error! Java won't let you do this.
String msg = messageBox.get(); // No casting needed
System.out.println("Message: " + msg);
// 2. The SAME class used for Integers
Box<Integer> numberBox = new Box<>();
numberBox.add(42);
int num = numberBox.get();
System.out.println("Number: " + num);
// 3. A Generic Method example
printArray(new String[]{"Java", "is", "cool"});
printArray(new Integer[]{1, 2, 3});
}
// A Generic Method that can print any type of array
public static <E> void printArray(E[] elements) {
for (E element : elements) {
System.out.print(element + " ");
}
System.out.println();
}
}Expected Output:
Message: Secret Message
Number: 42
Java is cool
1 2 3Generics are why the Collections Framework (like ArrayList) is so powerful. It allows Java to provide high-performance data structures that are also extremely safe to use. When you start building complex systems, Generics allow you to write "Clean Code" that is easy for other developers to understand without guessing what data is inside your variables.
Common Convention: You’ll see letters like
T(Type),E(Element),K(Key), andV(Value) used as placeholders. These are just names, but sticking to them makes your code look professional.