In: Computer Science
You'll implement a completely generic version of an algorithm to find the maximum of an array. Unlike in the past, when our algorithm only worked for int[] or double[], this version will work on any Java objects that are comparable, specifically any Java object that implements the Comparable interface. Create a public class named Max with a single class method named max. max should accept an array of Objects that implement Comparable and return the maximum. If the array is null or empty, you should return null.
Explanation:I have implemented the Max class with the max() method that accepts a generic array that implements the Comparable object.I have shown the output of the program, please find the images attached with the answer.Please upvote if you liked my answer and comment if you need any modification or explanation.
//code starts
import java.util.Arrays;
public class Max {
public static <T extends Comparable<T>>
T max(T[] arr) {
T maxElement = arr[0];
if (arr == null || arr.length ==
0)
return
null;
for (T arrayElement : arr) {
if
(arrayElement.compareTo(maxElement) > 0) {
maxElement = arrayElement;
}
}
return maxElement;
}
public static void main(String[] args) {
Integer[] integerArray = {55, 23,
135, -44, 24443, 2224, 1234, 67};
Double[] doubleArray = {251.13,
2667.26, 3123.33, 54124.4, 124.45,
3124.53, 1124.54, 65.78};
Character[] characterArray = {'H',
'A', 'K', 'T', 'O', 'S', 'F', 'W'};
System.out.println("The maximum
element in : "
+ Arrays.toString(integerArray) + " is " +
max(integerArray));
System.out.println("The maximum
element in : "
+ Arrays.toString(doubleArray) + " is " +
max(doubleArray));
System.out.println(
"The maximum element in : " +
Arrays.toString(characterArray)
+ " is " +
max(characterArray));
}
}
Output: