There are two issues in your code:
The Comparable::compareTo
method doesn't return boolean
but int
. Here is the description of the method:
Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
In the foregoing description, the notation sgn(expression) designates the mathematical signum function, which is defined to return one of -1, 0, or 1 according to whether the value of expression is negative, zero or positive.
You cannot instantiate the generic object such as new E()
. Check Instantiating generics type in java.
This is a way to go:
public static <E extends Comparable<E>> E getMaxElement(E[][] list) {
E theMaximumElement = list[0][0]; // initial value (the first one)
for (final E[] array : list) {
for (final E e : array) {
if (theMaximumElement.compareTo(e) < 0) // comparison is against 0
theMaximumElement = e; // setting the new maximum value
}
}
return theMaximumElement; // returning it
}
The only condition is that an element list[0][0]
exists, i.e. the arrays are not empty. Otherwise, you should modify the solution to use Optional<E>
since the maximum is not always found (empty arrays).
As of Java 8, there is a simple way to handle such use cases using java-stream:
Optional<E> optionalmaximum = Arrays.stream(list) // Stream<E[]>
.flatMap(Arrays::stream) // Stream<E>
.max(Comparator.naturalOrder()); // Optional<E>