You can only use comparison operators on numeric types. If you want to compare generic types, you'll have to ensure they implement Comparable
, and call Comparable.compare()
:
public static <T extends Comparable<? super T>> T largestInArray(T[] inputArray) {
//...
if (inputArray[i].compareTo(largest) > 0) {
//...
}
compareTo()
will return 0 for equal values, < 0 if the target object has precedence, and > 0 if the argument has precedence.
Alternatively, you can use a custom Comparator
instead of relying on the natural order:
public static <T> T largestInArray(T[] inputArray, Comparator<? super T> comparator) {
//...
if (comparator.compare(inputArray[i], largest) > 0) {
//...
}
compare()
works similar to compareTo()
above.
Note that these are both already implemented as Collections
helpers, which you can easily call by wrapping the array:
Collections.max(Arrays.asList(inputArray)/*, comparator*/)