Back to Lessons

Generics in Java Collections

April 5, 2026

Java Generics

Type-safe collections preventing ClassCastException at compile time.

Generics Example

List strings = new ArrayList<>(); // Diamond operator
strings.add("Java");
// strings.add(123); // Compile error!

List wildcardList;           // Any type
List numbers; // Upper bound
List 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.