Generics in Java

  • Facebook
  • Google
  • LinkedIn
  • Twitter

Generics are one of the most important features in Java language. Generics allow a type or method to operate on objects of various types while providing compile-time type safety and remove the risk of ClassCastException at runtime.

For example ArrayList of String will only contain String object and if anybody want to try to put Integer or other object then compiler will complain but this was possible before Java 5 same code will add and compile without any problem but will fail at runtime which was not good. Generics allows Java programmer to write more robust and type-safe code. It gives you more readability from code.

Using Generics features you can set the type of the collection to what kind of objects can be inserted into the collection. And then you don't need to cast the values you obtain from the collection. Example using Java's Generic's features:

List<String> strings = new ArrayList<String>();
strings.add("a String");
String aString = strings.get(0);

It is checked at compile time so that problem will not occur at runtime. This is good feature came in java 5 and it is far better to handle the problem at compile time than runtime. Below is the example which gives compile time error.

List<String> list = new ArrayList<String>();  
list.add("hello");  
list.add(32);//Compile Time Error  

Map example using Generics.

import java.util.*;  
class MapGeneric{  
public static void main(String args[]){  
Map<Integer,String> map=new HashMap<Integer,String>();  
map.put(1,"mukarram");  
map.put(2,"shariq");  
  
Set<Map.Entry<Integer,String>> set=map.entrySet();  
  
Iterator<Map.Entry<Integer,String>> itr=set.iterator();  
while(itr.hasNext()){  
Map.Entry e=itr.next();//there is no need to typecasting  
System.out.println(e.getKey()+" "+e.getValue());  
}  
  
}}  
Output:
1 mukarram
2 shariq 

Generic class

A class that refers to any type is called as generic class. Here, we are using T type parameter to create the generic class of specific type.

class Gen<T>{
	T ob; //an object of type T is declared
	Gen(T o) //constructor
	{
	 ob = o;
	}
	public T getOb()
	{
	 return ob;
	}
}
	
class Test{
	public static void main (String[] args)
	{
	 Gen <Integer> iob = new Gen<Integer>(100); 
//instance of Integer type Gen Class. int x = iob.getOb(); System.out.print in(x); Gen <String> sob = new Gen<String>("Hello");
//instance of String type Gen Class. String str = sob.getOb(); } }

Output :

   100
   Hello
      Advertisements