Java Program to Find the Maximum Value From the Given Type of Elements Using Generics

Aim:

To write a java program to find the maximum value from the given type of elements using a generic function.

Procedure:

  1. Create a class Myclass to implement generic class and generic methods.
  2. Get the set of the values belonging to specific data type.
  3. Create the objects of the class to hold integer,character and double values.
  4. Create the method to compare the values and find the maximum value stored in the array.
  5. Invoke the method with integer, character or double values . The output will be displayed based on the data type passed to the method.

Program:

class MyClass<T extends Comparable<T>>
{
T[] vals;
MyClass(T[] o) 
{ 
vals = o;
}
public T min()
{
T v = vals[0];
for(int i=1; i < vals.length; i++)
if(vals[i].compareTo(v) < 0) 
v = vals[i];
return v;
}
public T max() 
{
T v = vals[0];
for(int i=1; i < vals.length;i++)
if(vals[i].compareTo(v) > 0) 
v = vals[i];
return v;
}
}
class gendemo 
{
public static void main(String args[])
{
int i;
Integer inums[]={10,2,5,4,6,1};
Character chs[]={'v','p','s','a','n','h'}; 
Double d[]={20.2,45.4,71.6,88.3,54.6,10.4};
MyClass<Integer> iob = new MyClass<Integer>(inums);
MyClass<Character> cob = new MyClass<Character>(chs);
MyClass<Double>dob = new MyClass<Double>(d);
System.out.println("Max value in inums: " + iob.max());
System.out.println("Min value in inums: " + iob.min());
System.out.println("Max value in chs: " + cob.max());
System.out.println("Min value in chs: " + cob.min());
System.out.println("Max value in chs: " + dob.max());
System.out.println("Min value in chs: " + dob.min());
}
}

Output:

Result:

Thus a java program to find the maximum value from the given type of elements has been implemented using generics and executed successfully.

Leave a Comment