Generics - interfaces and arrays

 

// Example – Generic programming and Interface

// Minimum and Maximum element in an array

 

interface MinMax<T1 extends Comparable<T1>>

{

     public void fnMin();

     public void fnMax();

}

 

class Gen<T1 extends Comparable<T1>> implements MinMax<T1>

{

     T1 min, max;

     T1 [] Arr;

    

     Gen(T1 [] A)

     {

          Arr = A;

     }

    

     public void fnMin()

     {

          min = Arr[0];

          for(int i = 1;i<Arr.length;i++)

              if(Arr[i].compareTo(min) < 0 )

                   min = Arr[i];

     }

    

     public void fnMax()

     {

          max = Arr[0];

          for(int i = 1;i<Arr.length;i++)

              if(Arr[i].compareTo(max) > 0 )

                   max = Arr[i];

     }

    

 

     public void fnDisplay()

     {

          System.out.print("\n\nArray elements : ");

          for(int i = 0;i<Arr.length;i++)

              System.out.print(Arr[i]+"\t");

          System.out.print("\nMinimum element = "+min);

          System.out.print("\nMaximum element = "+max);

     }

}

 

public class Generics_Demo

{

     public static void main(String as[])

     {

          Integer [] A1 = {2,4,1,6,5,3};

          Double []A2 = {2.3, 5.6, 1.3, 4.3};

          String []A3 = {"CSE","IT","CIVIL","EEE","AUTO"};

         

          Gen<Integer> g1 = new Gen<Integer>(A1);

          g1.fnMin();

          g1.fnMax();

          g1.fnDisplay();

                  

          Gen<Double> g2 = new Gen<Double>(A2);

          g2.fnMin();

          g2.fnMax();

          g2.fnDisplay();

         

          Gen<String> g3 = new Gen<String>(A3);

          g3.fnMin();

          g3.fnMax();

          g3.fnDisplay();

     }

}

No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu