Search⌘ K

Solution Review: Finding Max in an Array

Understand how to write a generic Java method that finds the maximum value in an array by using the Comparable interface. This lesson helps you apply generics for flexible, type-safe code that works with various data types while mastering core concepts of comparison and traversal.

We'll cover the following...

Given solution #

Java
class FindMax {
public static < T extends Comparable < T >> T array_max(T data[], int n) {
T max = data[0];
int i;
for (i = 1; i < n; i++) {
if (max.compareTo(data[i]) < 0) {
max = data[i];
}
}
return max;
}
public static void main( String args[] ) {
Integer[] inputs1 = {2,8,20,3,4};
Double[] inputs2 = {2.7,3.8,5.5,6.7,9.7};
System.out.println(array_max(inputs1,5));
System.out.println(array_max(inputs2,5));
}
}

Explanation

  • public static <T extends Comparable<T>> T array_max(T data[], int n)

    A static function is defined that extends the Comparable class (already implemented in Java) since we use a comparison function later in the program. T ...