Introduction of Generics in Java

Introduction

 
In this article, we are going to describe a new concept of Java which was introduced in J2SE 5.0. In this the system allows a type or method to operate on objects of various types while providing compile-time safety. Generics allow you to abstract over types. In other words, Generics provide a mechanism for annotating type information for the use of the compiler. The most common examples are container types, such as those in the Collections hierarchy.
 
mindMap.jpg

Problem where the need for Generics 

 
1: List myIntList =new LinkedList();
2: myIntList.add(new Integer(0));
3: Integer x = (Integer) myIntList.iterator().next();
 
In the first line, we simply make the object List class a data container also. And its second line is showing you addition of an integer value to this container and after seeing this line the programmer knows what kind of data has been placed into the particular list. The third line shows that a cast is required because the compiler can only guarantee that an Object will be returned by the iterator. To ensure the assignment to a variable of type Integer is type-safe.
 
Now you can solve the above problem with the help of generics as following code
 
List<Integer>myIntList new LinkedList<Integer>();
myIntList.add(newInteger(0);
Integer x = myIntList.iterator().next()
 
In the first line, we declare the type of object myIntList. After this declare <Integer> since your list is not a general type list but it is a list of Integers and with the help of Generics you can specify your object of any type. And the typecast is not need in the third line.
 

Basic Syntax Overview

 
You are also able to declare your own Generics class interface and methods. The following table shows the syntax of how you can use your own Generics. But Generics also allow primitive types that you can directly use.
 
  Syntax
Parameterized Type Vector<String> stringVector = new Vector<String>
List<Integer> integerList = new List<Integer>
Interface interface List<Element> implements MyInterface{...}
Class class MyList<Element> {...}
class MyList<Element> implements List<Element> {...}
Method boolean containsBoth(Element a, Element b);
static <Element> boolean swap(List<Element> list, int i, int j);
 

Advantages of Generics

 
In the Generic you can achieve polymorphic behavior. But with strong static type-checking conditions, the compiler knows that the two lists are different because they store different types of elements, and these lists are guaranteed to contain only a similar type set of elements. Using generics this time.
 
Simple Example
  1. import java.util.LinkedList;  
  2. import java.util.Collections;  
  3. import java.util.Iterator;  
  4. public class GenericsDemo {  
  5.  static public void main(String[] args) {  
  6.   LinkedList < String > strList = new LinkedList < String > ();  
  7.   LinkedList < Integer > intList = new LinkedList < Integer > ();  
  8.     
  9.   intList.add(new Integer(1));  
  10.   intList.add(new Integer(2));  
  11.   strList.add(new String("I am a abhishek"));  
  12.   strList.add(new Integer(1)); // causes a compilation error  
  13.   Iterator < Integer > listIterator = integerList.iterator();  
  14.   String item;  
  15.     
  16.   while (listIterator.hasNext()) {  
  17.    item = listIterator.next(); // causes a compilation error  
  18.   }  
  19.  listIterator = strList.iterator(); // causes a compilation error  
  20.   while (listIterator.hasNext())  
  21.   {  
  22.    item = listIterator.next();  
  23.   }  
  24.  }  
  25. }   
OUTPUT
 
error.gif
 
In the upper program code, you will show the error in the three lines at compile time.
 
1: The first error in line 15stringList.add(new Integer(1)) is because its object type is specified by Generics and this object allows only adding a string, not another type.
 
2: And you found the second error in the line 20 item = listIterator.next(),  by the generic, we type specified the object of the listIterator that takes a return integer value but we are trying to store in a string type of variable; that is why it is giving an error.
 
3: And the last error you found inline 25 is the line is listIterator = stringList.iterator(); and it gives an error like a  genericsExample2.java:33: incompatible types found: java.util.Iterator<java.lang.String>required:java.util.Iterator<java.lang.Integer.
 
After correcting all the errors in the preceding example:
  1. import java.util.LinkedList;  
  2. import java.util.Collections;  
  3. import java.util.Iterator;  
  4.   
  5. public class GenericsDemo1 {  
  6.  static public void main(String[] args) {  
  7.   LinkedList < String > strList = new LinkedList < String > ();  
  8.   LinkedList < Integer > intList = new LinkedList < Integer > ();  
  9.   
  10.   intList.add(new Integer(1));  
  11.   intList.add(new Integer(2));  
  12.   
  13.   strList.add(new String("I am a abhishek"));  
  14.   strList.add(new String("hello")); //  
  15.   
  16.   Iterator < Integer > listIterator = intList.iterator();  
  17.   int item;  
  18.   System.out.print("Integer list values   ");  
  19.   while (listIterator.hasNext())  
  20.   
  21.   {  
  22.    item = listIterator.next(); // causes a compilation error  
  23.    System.out.print(+item + "\t");  
  24.   }  
  25.   System.out.println("");  
  26.   Iterator < String > StrIterator = strList.iterator();  
  27.   String s = null;  
  28.   System.out.println("String list values   ");  
  29.   while (StrIterator.hasNext()) {  
  30.    s = StrIterator.next();  
  31.    System.out.print(s + "\t");  
  32.   }  
  33.  }  
  34. }