Generic Programming - maximum value in array

// Generic programming
// Maximum value in array

/*
Create a Java program that finds the maximum value based on the given type of elements using generic functions in java.
*/


class Gen<T1 extends Comparable<T1>>
{
     T1 x[];
    
     Gen(T1 []v1)
     {
          x = v1;
     }
    
     public void fnDisplay()
     {
          System.out.println("Array elements");
          for(int i = 0;i<x.length;i++)
              System.out.println(x[i]);
     }
    
     public void fnFind()
     {
          T1 max = x[0];
          for(int i = 1;i<x.length;i++)
              if(x[i].compareTo(max) > 0 )
                   max = x[i];
             
          System.out.println("Maximum value in array = "+max);
     }
}

class GP2
{
     public static void main(String as[])
     {
          Integer [] ia = {8,4,2,6};
          Gen<Integer> g1 = new Gen<Integer>(ia);
          g1.fnDisplay();
          g1.fnFind();
         
          String []sa = {"CSE", "IT", "EEE", "ECE", "AUTO"};
          Gen<String> g2 = new Gen<String>(sa);
          g2.fnDisplay();
          g2.fnFind();
         
          Double [] da = {1.3,4.6,2.9,9.6,5.6,7.3};
          Gen<Double> g3 = new Gen<Double>(da);
          g3.fnDisplay();
          g3.fnFind();
     }
}

No comments:

Post a Comment

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

Anu