Generics in Java

<< Previous Chapter Next Chapter >>
Generics in Java:

We can make generic class, method and constructor, by creating a generic data type which we can use for all type of data (int, float, double, etc.). Generics are used for strict type checking introduced in jdk 1.5 version.

We cannot create a reference of one generic object of particular type to another generic object of other type.

Create a java file GenericsDemo.java inside dev21century.generics package

package dev21century.generics;

class Gen<T>
{
     T obj; //declaring object of type T
     Gen(T o)
     {
           obj = o;
     }
     T getOb()
     {
           return obj;
     }
     void showType()
     {
           System.out.println("Type of T is " + obj.getClass().getName());
     }
}

public class GenericsDemo {
  public static void main(String[] args) {
   Gen<Integer> iob = new Gen<Integer>(80);
   iob.showType();
   int y = iob.getOb();
   System.out.println("value : " + y);
   Gen<String> strOb = new Gen<String>("Generic Test");
   strOb.showType();
   String str = strOb.getOb();
   System.out.println("value = " + str);
  }
}

Output:

Bounds in generics:
In below case, any class must be a subclass of Number.

Example:
Create a java file BoundsDemo.java inside dev21century.generics package

package dev21century.generics;

class Stats<T extends Number>
{
       T[] nums;
       Stats(T[] o)
       {
              nums = o;
       }
      
       double average()
       {
              double sum = 0.0;
              for(int i=0;i<nums.length;i++)
                     sum += nums[i].doubleValue();
              return (sum/nums.length);
       }
}
public class BoundsDemo {
public static void main(String args[])
{
       Integer inums[] = {1,2,3,4,5};
       Stats<Integer> tab = new Stats<Integer>(inums);
       double y = tab.average();
       System.out.println("Avegare is: " + y);
       Double dnums[] = {1.1,1.2,1.3,1.4};
      
       Stats<Double> dob = new Stats<Double>(dnums);
       double w = dob.average();
       System.out.println("double average is: " + w);
}
}

Output:

            Stats<String> sob = new Stats<String>(inums);

Above statement will give compiler error “Bound mismatch: The type String is not a valid substitute for the bounded parameter <T extends Number> of the type Stats<T>” this is because String class is not a child of Number.

Generic Arrays:

Example:
Create a java file GenArrays.java inside dev21century.generics package

package dev21century.generics;
class Gen<T extends Number>
{
       T obj;
       T[] vals;
       Gen(T o, T[] nums)
       {
              obj = o;
              vals = nums;
       }
}

public class GenArrays {
  public static void main(String[] args) {
             
    Integer n[] = {1,2,3,4,5};
    Gen<Integer> iob = new Gen<Integer>(50, n);
    /*can't create an array of type specific
         generic reference, following statement is not allowed
    */
    //Gen<Integer> gen[] = new Gen<Integer>[10];
    //instead, following is allowed
    Gen<?> gens[] = new Gen<?>[10];
             
    gens[0] = new Gen<Integer>(10,n);
    Double[] d2 = new Double[]{1.2,2.3,4.1};
    gens[1] = new Gen<Double>(2.4, d2);
    System.out.println("Integer values: ");
    for(int i =0;i<gens[0].vals.length;i++)
       {
          System.out.print(gens[0].vals[i] + " ");
       }
    System.out.println();
    System.out.println("Double values: ");
    for(int i =0;i<gens[1].vals.length;i++)
      {
       System.out.print(gens[1].vals[i] + " ");
      }
    System.out.println();
  }
}

Output:

Local argument as generic - constructor:
Example:

Create a java file GenConsDemo.java inside dev21century.generics package

package dev21century.generics;

class GenCons
{
       private double val;
       <T extends Number> GenCons(T arg)
       {
              val = arg.doubleValue();
       }
       void showVal()
       {
              System.out.println("val = " + val);
       }
}

public class GenConsDemo {
   public static void main(String[] args) {
     //GenCons test1 = new GenCons('d');
     //above line will give Bounds mismatch error
             
     GenCons test = new GenCons(100);
     GenCons test2 = new GenCons(123.5);
     test.showVal();test2.showVal();
  }
}

Output:

Generic method arguments – generic method to which we can supply any type of arguments.
Example:

Create a java file GenConsDemo.java inside dev21century.generics package

package dev21century.generics;

public class GenMethDemo {

 //determine if an object is in an array
      
  static <T, V extends T> boolean isIn(T x, V[] y)
   {
    for(int i=0;i<y.length;i++)
      if(x.equals(y[i]))
        return true;
             
    return false;
   }
   static <T extends Number> double add(T x, T y)
   {
    double d = x.doubleValue() + y.doubleValue();
    return d;
   }
   public static void main(String[] args) {

    //use isIn() method on integer
    Integer nums[] = {1,2,3,4,5,6};
             
    if(isIn(2,nums))
       System.out.println("2 is in nums");
    if(!isIn(9,nums))
       System.out.println("9 is not in nums");
             
    //using isIn method on String
    String strs[] = {"one", "two", "three", "four"};
    if(isIn("two", strs))
       System.out.println("two is in nums");
    if(!isIn("seven", strs))
       System.out.println("seven is not in nums");
             
    System.out.println("10 + 20 = " + add(10,20));
    System.out.println("10.5d + 20.5d = " + add(10.5d,20.6d));
  }
}

Output:

Generic & Non Generic relationships:

Example:
Create a java file GenHireDemo.java inside dev21century.generics package

package dev21century.generics;
class NonGen
{
       int num;
       NonGen(int i)
       {
              num = i;
       }
       int getNum()
       {
              return num;
       }
}

//a generic class
class GenClass<T> extends NonGen
{
       T ob;//declare object of type T
              //pass the constructor a reference
              //to an object of type T
       GenClass(T o, int i)
       {
              super(i);
              ob = o;
       }
       T getOb()
       {
              return ob;
       }
}

public class GenHireDemo {
public static void main(String args[])
{
       //create a generic object for String
       GenClass<String> w = new GenClass<String>("Hello", 47);
       System.out.println(w.getOb()+ " ");
       System.out.println(w.getNum());
}
}

Output:


<< Previous Chapter Next Chapter >>



No comments:

Post a Comment