Sunday, December 11, 2016

Generics in Java

Java Generics are used to store only the specific type of objects. Generics are introduced in Java programming language in 2004 within the official version J2SE 5.0. It is written by angle brackets (< >) and it has three advantages. They are
  1. Type Safety
  2. No need to use Type-Casting
  3. Compile-time checking
Before generics, we can hold any type of objects but in generics it is strictly to use only the type(String, Integer, Float etc) you want to store.

For simplicity, I'm going to use ArrayList.

Syntax :

      Class or Interface<Type>

Example : 

      ArrayList<String>

Code Snippet :  


import java.util.*;

class TestGenerics1{

    public static void main(String args[]){

     ArrayList arrayListGenerics = new ArrayList();
    
     //storing values to arrayListGenerics object
     arrayListGenerics.add("praveen");
     arrayListGenerics.add("naveen");
     arrayListGenerics.add("ajith");
     arrayListGenerics.add("gopal");
    //arrayListGenerics.add(32);//compile time error

    String myValues = arrayListGenerics.get(1);//No need for type casting
    System.out.println("Data is : "+myValues);

    Iterator itr = arrayListGenerics.iterator();

    while(itr.hasNext()){

         System.out.println(itr.next());
     }
   }
}


OUTPUT :

Data is : naveen
praveen
naveen
ajith
gopal

   
 
Location:India, Tamil Nadu, Tuticorin Thoothukudi, Tamil Nadu, India