Tutorials

Java Generics


Generics


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:

Ge

 

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.

 

Java Generics by tutorialsinhand.com

 

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

  1. Generics increases type-safety in java
  2. Type-Checking done at compile time to report any irrelevant data type stored.
  3. Generics enhances reusability of the code.


Please Share this page
Views : 100
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!