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 need of 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 an add 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 above problem with help of generics as following code


L
ist<Integer>myIntList = new LinkedList<Integer>();

myIntList.add(new Integer(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 specifiy your object of any type. And the type cast 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
Paramaterized 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

import java.util.LinkedList;

    import java.util.Collections;

    import java.util.Iterator;

 

    public class GenericsDemo

            {

        static public void main(String[] args) {

        LinkedList<String>  strList  = new LinkedList<String>();

        LinkedList<Integer> intList = new LinkedList<Integer>();

 

        intList.add(new Integer(1));

        intList.add(new Integer(2));

 

        strList.add(new String("I am a abhishek"));

        strList.add(new Integer(1)); // causes a compilation error

 

        Iterator<Integer> listIterator = integerList.iterator();

        String item;

        while(listIterator.hasNext()) {

        item = listIterator.next(); // causes a compilation error

          }

 

      listIterator = strList.iterator(); // causes a compilation error

 

     while (listIterator.hasNext())
         {

        item = listIterator.next();

         }

   }

   }

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 15 stringList.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 in line 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:

import java.util.LinkedList;

import java.util.Collections;

import java.util.Iterator;

 

public class GenericsDemo1

   {

    static public void main(String[] args)

    {

    LinkedList<String>  strList  = new LinkedList<String>();

    LinkedList<Integer> intList = new LinkedList<Integer>();

 

    intList.add(new Integer(1));

    intList.add(new Integer(2));

 

    strList.add(new String("I am a abhishek"));

    strList.add(new String("hello")); //

 

    Iterator<Integer> listIterator = intList.iterator();

    int item;

    System.out.print("Integer list values   ");

    while(listIterator.hasNext())
        {

        item = listIterator.next(); // causes a compilation error

        System.out.print(+item+"\t");

        }

    System.out.println("");

    Iterator<String> StrIterator = strList.iterator();

    String s=null;

    System.out.println("String list values   ");

    while (StrIterator.hasNext())

          {

    s = StrIterator.next();

    System.out.print(s+"\t");

          }

    }

   } 
 

OUTPUT

cmdright.gif


Resources


Generics in .NET
Implementing Internationalization in JAVA
Introduction of Servlet in JAVA
Generics in C#
An Introduction to C# Generics