In the last chapter of this java tutorial, we have learned about the problems without using Generics.
Here we are going to learn about using Generics and its benefits.
Generics restricts us from inserting different data type values in collections, classes and interfaces.
When we use generics, we define the data type value the collection will hold. We can define the type by passing the data type in the angle bracket as shown below.
For example, if we want our list to hold only String value then we need to write:
Similarly you can define data type like Integer, Double, Float, Object, etc as parameter with the Collection, Class or Interface.
Java Generics example:
Given below is the java program showing use of Generics to make our code type safe.
Now try to insert other data type in the above array list after aplying generics.
See the red lines below add.
This is the error by compiler during compile time.
It warns the coder that the inserted values are not acceptable in this list as it is informed to hold only String value. That is why "Java" which is String value is not reported by compiler.
Advantages of Generics
Generics increases type-safety in java
Type-Checking done at compile time to report any irrelevant data type stored.
Generics enhances reusability of the code.