Tuesday, 11 December 2012

Generics - Java

Generics are mainly used for creating type safe collections and for avoiding code repetition. It also helps us to make our code more readable. We can use generic methods as well as generic classes. This is one of the new feature in JDK5.
Here I am giving few examples of generics in java..

Avoiding code repetition:
public class Test
{                   
    public static <E extends Comparable<E>> E max( E x, E y, E z)
    {
        E max = x;
        if(max.compareTo(y) < 0)
        {
            max = y;
        }
        if(max.compareTo(z) < 0)
        {
            max = z;
        }
        return max;
    }
    public static void main( String args[])
    {
        System.out.print("\nMax : " + max(1, 2, 3));
        System.out.print("\nMax : " + max(1.0, 2.3, 3.6));
        System.out.print("\nMax : " + max("Abc", "Pqr", "Xyz"));
    }
}


Here you can see that we are using same method to compare integers, floats and strings. In this way generics avoid code repetition an this is making our code more redable.


Type safe collections:
 import java.util.ArrayList;
public class Test
{                   
    ArrayList<String> al;
    public Test()
    {
        al = new ArrayList<String>();
        al.add("Test 1");
        //al.add(1); This will create compile time error.
        al.add("Test2");
        System.out.print("Array list is : " + al);
    }
    public static void main(String args[])
    {
        new Test();      
    }
}


Here in the above code you can see that we are using ArrayList and we are making it type safe. Here our ArrayList will be able to store only strings. If you are trying to add integer then it will create compile time error.


Generic classes:
class Test<E>
{
    private <E extends Comparable<E>>void maxTest(E x, E y)
    {
        E max = x;
        if(max.compareTo(y) < 0)
            max = y;
        System.out.print("\nMax is : " + max);
    }
    public static void main(String args[])
    {
        Test<String> t1 = new Test<String>();
        t1.maxTest(1, 2);
      
        Test<String> t2 = new Test<String>();
        t2.maxTest(1.2, 2.7);
      
        Test<String> t3 = new Test<String>();
        t3.maxTest("A", "B");
    }
}


In this way we can write generic classes.

Here we can say that generics is mainly used for type safe collections, avoiding code repetition and making code more readable.

No comments:

Post a Comment