How Java Ensures Type Safety in Collections Using Generics
How Java Ensures Type Safety in Collections Using Generics
Type safety in Java ensures that only a specific type of data can be stored in a collection, preventing
ClassCastException at runtime. Prior to Java 5, collections stored Object references, requiring manual
type casting and risking runtime errors. Generics (introduced in Java 5) enforce type safety at
compile time.
Generics allow specifying the type of elements a collection can store. This eliminates:
ClassCastException → No need for explicit type casting.
Runtime Errors → Errors are caught at compile time.
Code Readability & Maintainability → Clearer and self-documenting code.
Before Java 5, collections stored objects of any type, requiring explicit casting:
import java.util.ArrayList;
list.add("Hello");
Using generics, we define the type a collection can store, ensuring type safety at compile time.
import java.util.ArrayList;
public class WithGenerics {
list.add("Hello");
System.out.println(str);
Advantages:
✔ No ClassCastException
✔ Compile-time Type Checking
✔ Cleaner Code (No Need for Explicit Casting)
import java.util.HashMap;
map.put(1, "One");
map.put(2, "Two");
System.out.println(value);
}
Example with LinkedList<T>
import java.util.LinkedList;
numbers.add(3.14);
numbers.add(2.71);
System.out.println(pi);
import java.util.ArrayList;
System.out.println(num);
intList.add(10);
intList.add(20);
ArrayList<Double> doubleList = new ArrayList<>();
doubleList.add(5.5);
doubleList.add(2.2);
Wildcard ? extends Number allows passing any subclass of Number (Integer, Double, etc.).
8. Conclusion
• Compile-time type checking ensures only compatible types are stored in collections.
• Eliminates explicit type casting, making code cleaner and more readable.
• Wildcards (? extends & ? super) provide flexibility when working with generics.