Chaz32621 - 1 year ago 72

Java Question

I would like to modify the following method so its arguments can be of any type that implements the

`Comparable`

`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>>`

Answer Source

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;
}
```