Use Of Generic in Java

In  this blog I will be explaining about the Generic keyword in java.

Generic  keyword means more type safety. It helps to write type- safe collection.The use of generic is of utter importance. Before the generic was used, if you are trying to create the arraylist ,then you just need to write -:

ArrayList list=new ArrayList();
A Digrammatic Representation of ArrayList

Before Generic

Img1.jpg

In this arraylist, you can save object of class Cat, Dog, Fish,  Lion. The list becomes the mixture of  objects of diiferent class and it is difficult to perform any operation on the list. So, the introduction of generic has included an element  <E > that we have to define while creating arraylist , like

The Syntax of creating ArrayList is-:

ArrayList<E> list1= new ArrayList<E>();
 
AFTER GENERIC

Img2.jpg 

So, above arraylist will be written as-:

ArrayList <CAT> list=new ArrayList<CAT>() ;
 
In this arraylist,  Objects of only Cat class will be saved and now you can perform various operations on it. I hope this article was useful to you and thank you for reading it.

Ebook Download
View all
Learn
View all