Objective: Write a java program to find the maximum value from the given type of elements using a generic function.
Code:
import java.util.Arrays;
import java.util.Collections;
public class GenericMaxFinder {
// Generic method to find the maximum element in an array
public static <T extends Comparable<T>> T findMax(T[] elements) {
if (elements == null || elements.length == 0) {
throw new IllegalArgumentException("Array must not be null or empty");
}
return Collections.max(Arrays.asList(elements));
}
public static void main(String[] args) {
// Example with Integer array
Integer[] intArray = {3, 7, 2, 9, 5};
System.out.println("Maximum Integer: " + findMax(intArray));
// Example with Double array
Double[] doubleArray = {4.5, 2.3, 9.8, 1.2};
System.out.println("Maximum Double: " + findMax(doubleArray));
// Example with String array
String[] stringArray = {"apple", "orange", "banana", "mango"};
System.out.println("Maximum String: " + findMax(stringArray));
}
}
Output:
No comments:
Post a Comment