In: Computer Science
for java,
Behold, the power of interfaces! On this homework problem 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. You will probably need to review the documentation for Comparable.
Hi. I have answered a very similar question before. Here is the completed code for this problem, including a class for testing. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks
//Max.java
public class Max {
// required method
public static <E extends Comparable<E>> E max(E[] objects) {
// if array is null or is empty, returning null
if (objects == null || objects.length == 0) {
return null;
}
// otherwise setting first element as maxVal
E maxVal = objects[0];
// looping through remaining elements
for (int i = 1; i < objects.length; i++) {
// if current element is greater than maxVal, setting current
// element as new maxval
if (objects[i].compareTo(maxVal) > 0) {
maxVal = objects[i];
}
}
// returning maxVal
return maxVal;
}
}
//Test.java
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
// creating arrays of different Comparable types
String[] names = { "John", "Alice", "Damien", "Bran" };
Integer[] integers = { 1, 0, 3, -2, 8, 5 };
Double[] doubles = { 3.0, 5.9, 2.9, 1.5, 6.6, 4.3, 1.1 };
Character[] letters = { 'A', 'Z', 'D', 'X' };
// displaying arrays and max value of each of them
System.out.println("Names: " + Arrays.toString(names));
System.out.println("Max value: " + Max.max(names));
System.out.println("Integers: " + Arrays.toString(integers));
System.out.println("Max value: " + Max.max(integers));
System.out.println("Doubles: " + Arrays.toString(doubles));
System.out.println("Max value: " + Max.max(doubles));
System.out.println("Letters: " + Arrays.toString(letters));
System.out.println("Max value: " + Max.max(letters));
}
}
/*OUTPUT*/
Names: [John, Alice, Damien, Bran]
Max value: John
Integers: [1, 0, 3, -2, 8, 5]
Max value: 8
Doubles: [3.0, 5.9, 2.9, 1.5, 6.6, 4.3, 1.1]
Max value: 6.6
Letters: [A, Z, D, X]
Max value: Z