简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM