Generics and arrays

 // Generic programming

// Find min value in Arrays

 

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 min = x[0];

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

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

                   min = x[i];

             

          System.out.println("Minimum value in array = "+min);

     }

}

 


 

class Generics_Demo

{

     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"};

          Gen<String> g2 = new Gen<String>(sa);

          g2.fnDisplay();

          g2.fnFind();

     }

}

No comments:

Post a Comment

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

Anu