What is benefit of Generics in Collections Framework
Generics in java enable types to be parameterized when defining classes, interfaces and methods. Its like familiar formal parameters used in when declare methods; type parameters provide way for us to re-use same code with different inputs parameters. Difference is that inputs to the formal parameters are values, while inputs to type parameters are types.
In java generics have many benefits over non-generic code:
- Stronger type check at code compiles time.
Java compiler applies strong type checking to the generic code and issue errors if code violates type safety or not. Fixing compile time errors are easier than fixing runtime errors, which could be difficult to find.
- Elimination of casting.
Below code snippet without generics requires casting:
When re-written using generics, code does not requires casting:
It enables us to implement generic algorithms.
By using generics, we could implements generic algorithms that could work on different types of collections, could be customized, and are also type safe and easier to read.
Check out all interview questions