General function max jstl

I need a max function in my jstl, so I write a static function and expose it in tld as a jstl function.

The problem is, I don't know what type of arguments will be, int, long, double, etc. Do I need to create a function for each data type? or maybe I can just write a function for paired and pray jstl will do the conversion for me?

edit2 : Never thought I thought the tld definition would be as simple as T max (T, T), but it is not. I have no idea how to make a tld definition for a generic method. I guess sick is just praying that jsp will convert my type correctly and use Math.max (double, double)

+1


a source to share


2 answers


Is it a maximum function, like Math.max()

(take two parameters, return more) or something like Arrays.sort()

(take an array, return largest value).

In the first case, the JSP EL will coerce the arguments to the correct types if possible.



In the second case, you need a separate method for each element type of the primitive type that you want to support.

+2


a source


try this:

public static <T extends Comparable<? super T>> T max(T a, T b) {
    if (a.compareTo(b) > 0) {
        return a;
    } else {
        return b;
    }
}

public static void main(String[] args) {
    System.out.println(max(20, 10));
    System.out.println(max(103.2, 120.2));
    // it works even on strings...
    System.out.println(max("aaa", "bbb"));  
    // ... and booleans...
    System.out.println(max(true, false));  
}

      



alternatively you can use standard Java classes like Collections

and Arrays

:

Collections.max(Arrays.asList(10, 20, 30, 40, 50));

      

+2


a source







All Articles