Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying a method so the arguments can be any type that implements Comparable

Tags:

java

generics

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?

like image 650
Chaz32621 Avatar asked Sep 29 '12 00:09

Chaz32621


1 Answers

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;
}
like image 54
arshajii Avatar answered Oct 20 '22 06:10

arshajii