Notes
Java Generics with Examples
Content of the notes (1)
Page 1
As we know that, Generics was added in Java 5 to provide compile-time type checking and removing the risk of ClassCastException that was common while working with collection classes.
The whole collection framework was re-written to use generics for type-safety. Let’s see in this post how generics help us using collection classes safely.
Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces, and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types.
Benefits of Generics
1. Stronger type checks at compile time
A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.
Example: In this example, List holds only a String type of objects in generics. It doesn’t allow to store other objects
List<String> list = new ArrayList<String>(); list.add("abc");
Information
- Description
- o k Note on Java Generics with Examples, created by Reyou App on 30/06/2023.
- Created by
- Reyou App · Jun 2023
- Updated
- Jun 30, 2023
- Views
- 0
- Rating