Generic PGM
Generic PGM
T[] vals;
MyClass(T[] o) {
vals = o;
}
min() Method:
Initializes v to the first element of the array.
Iterates through the array starting from the second element.
If the current element is less than v (using compareTo), it
updates v to the current element.
Returns the minimum value found.
max() Method:
Similar to min(), but checks if the current element is greater than
v to find the maximum value.
Main Class:
public class Gendemo {
public static void main(String args[]) {
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<>(inums);
MyClass<Character> cob = new MyClass<>(chs);
MyClass<Double> dob = new MyClass<>(d);
This class contains the main method, which is the entry point of the
program.
Three arrays are defined: inums, chs, and d containing Integer,
Character, and Double values, respectively.
Instances of MyClass are created for each array type, initializing them
with the respective arrays.
Output Statements:
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 dob: " + dob.max());
System.out.println("Min value in dob: " + dob.min());
}
}
Each System.out.println statement calls the max() and min() methods
of the MyClass instances and prints the results to the console.
Summary
This code defines a generic class MyClass that can handle arrays
of any type that implements Comparable.
It provides methods to find the minimum and maximum values
in the array.
The Gendemo class demonstrates the usage of MyClass with
Integer, Character, and Double arrays, printing their min and
max values.