Why We Need Generics In Java?
Generics are introduced in Java 5 for enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. They are implemented by Java compiler as a front-end conversion called erasure . The benefits of generic as follows:
- Elimination of Type Casting
- Stronger type checking at compile time
- Enabling programmers to implement generic algorithms
Elimination of Type Casting
Generics provide the type checking at compile time . Finding bugs in compile-time can save time for debugging java program, because compile-time bugs are much easier to find and fix. If you use generics , you need not to perform the type casting explicitly. Java compiler applies strong type checking if you use generics in your code and shows errors if the code violates the type safety. Thus removing the risk of ClassCastException .
In the above case we can see typecasting in last line.
Stronger type checking at compile time
Finding bugs in compile-time can save time for debugging java program, because compile-time bugs are much easier to find and fix. Java compiler applies strong type checking to generic code and issues errors if the code violates type safety.
The compiler is responsible for understanding Generics at compile time. Above code is checked at compile time, so it is guaranteed that no problem will occur at runtime.
Enabling developers to implement generic algorithms
By using generics , developers can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read.
- Java Interview Questions-Core Faq
- Important features of Java
- What is the difference between JDK and JRE?
- What gives Java its 'write once and run anywhere' nature?
- What is JVM and is it platform independent?
- What is Just-In-Time (JIT) compiler?
- What is the garbage collector in Java?
- What is NullPointerException in Java
- Difference between Stack and Heap memory in Java
- How to set the maximum memory usage for JVM?
- What is numeric promotion?
- What does it mean to be static in Java?
- What are final variables in Java?
- How Do Annotations Work in Java?
- How do I use the ternary operator in Java?
- What is instanceof keyword in Java?
- How ClassLoader Works in Java?
- What are fail-safe and fail-fast Iterators in Java
- What are method references?
- "Cannot Find Symbol" compile error