30 January 2013

Generics in Java


Java Generic methods and generic classes enable programmer to specify, with a single method declaration, a set of related methods or, with a single class declaration, a set of related types respectively.

Generic Methods:
Generic methods have type parameter section delimited by angle brackets (< and >) that precedes the methods return type.<E>
Example:

//Generic method example to print integer/double/character array using single generic method.
public class Test11 {

public static <E> void printArray(E[] ref)
{
System.out.println("started printing of data");
for(E element:ref)
{
System.out.println(element);
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Integer[] i1 = {2,4,6,8};
Double[] d1 = {1.2,3.4,5.6,7.8};
Character[] c1 = {'M','a','d','h','u'};
printArray(i1);
printArray(d1);
printArray(c1);
}

}

Bounded Type Parameters:

There may be times when you will want to restrict the kinds of types that are allowed to be passed to a type parameter. for example a method accepting numbers might only want to accept the instances of Number and its sub classes.

Example:

public class Test12 {

public static <T extends Comparable<T>> T max(T x, T y, T z)
{
T max = x;
if (max.compareTo(y) < 0)
max  = y;
if (max.compareTo(z) < 0)
max  = z;

return max;
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Integer comparison");
   System.out.printf("Max of elements %d %d %d is: %d\n", 3,4,5,max(3,4,5));
   System.out.println("double comparison");
   System.out.println("Max of elements is:"+max(3.5,4.7,5.9));

   System.out.println("String comparison");
System.out.printf("Max of elements %s %s %s is: %s","madhu" ,"Srilatha","Chandrakala",max("madhu","Srilatha","Chandrakala"));

}

}

Generic Classes:
A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section.

// Example for string classes
public class Test13<T> 
{

 private T t;

 public void add(T t) 
 {
   this.t = t;
 }

 public T get() 
 {
   return t;
 }

 public static void main(String[] args) 
 {
    Test13<Integer> integerBox = new Test13<Integer>();
    Test13<String> stringBox = new Test13<String>();
   
    integerBox.add(new Integer(10));
    stringBox.add(new String("Hello World"));

    System.out.printf("Integer Value :%d\n\n", integerBox.get());
    System.out.printf("String Value :%s\n", stringBox.get());
 }
}


No comments:

Post a Comment