Generics in Java act as a type-safety enforcement mechanism that allows you to specify the exact type of objects a class, interface, or method can operate on. They enable you to write reusable code without sacrificing type safety .
Type-Safety
Before generics (introduced in Java 5) it was not possible to specify the type of collections in Java. This led to many runtime exceptions, typically ClassCastException .
Without generics
List list = new ArrayList (); list . add ( "Hello" ); list . add ( 123 ); // Compiler allows this
// Requires casting, and crashes at runtime if the type is wrong String works = ( String ) list . get ( 0 ); String breaks = ( String ) list . get ( 1 ); // Throws ClassCastException!
Enter fullscreen mode
Exit fullscreen mode
With generics
List < String > list = new ArrayList <>();
list . add ( "Hello" ); list .…