Generics in Java Collections
Java Generics
Type-safe collections preventing ClassCastException at compile time.
Generics Example
Liststrings = new ArrayList<>(); // Diamond operator strings.add("Java"); // strings.add(123); // Compile error! List> wildcardList; // Any type List extends Number> numbers; // Upper bound List super Integer> integers; // Lower bound
Key Points
- Generics:
List<T>where T is type parameter. - Eliminates runtime casting errors.
- Wildcard
<?>for unknown types. - Type erasure: generics info removed at runtime.