Quick Answer
Implement type-safe collections and methods.
Understanding the Issue
Generics enable types (classes/interfaces) to be parameters. Provides compile-time type checking and eliminates casting. Use with collections, classes, methods.
The Problem
This code demonstrates the issue:
Java
Error
// Non-generic (unsafe)
List list = new ArrayList();
list.add("test");
Integer i = (Integer) list.get(0); // Runtime error
The Solution
Here's the corrected code:
Java
Fixed
// Generic solution
List<String> safeList = new ArrayList<>();
safeList.add("test");
String s = safeList.get(0); // Type safe
// Generic method
public <T> void printArray(T[] array) {
for (T element : array) {
System.out.println(element);
}
}
Key Takeaways
Generics improve type safety and reduce casting.