I would like to modify the following method so its arguments can be of any type that implements the Comparable
interface. The method’s return type should be the same as the type of its parameter variables.
public static int max(int a, int b) {
if (a >b)
return a;
else
return b;
}
So in modifying it, I could just use <T extends Comparable<T>>
, but how would I go about making the return types the same?
You essentially want something like this:
public static <T extends Comparable<T>> T max(T a, T b) {
int n = a.compareTo(b);
if (n > 0)
return a;
if (n < 0)
return b;
return a;
}
You can of course simplify this to the following (thank you to @pickypg for the notice):
public static <T extends Comparable<T>> T max(T a, T b) {
return a.compareTo(b) < 1 ? b : a;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With