Comparing the values of two generic Numbers

后端 未结 12 1761
小鲜肉
小鲜肉 2020-11-27 04:48

I want to compare to variables, both of type T extends Number. Now I want to know which of the two variables is greater than the other or equal. Unfortunately I

12条回答
  •  时光取名叫无心
    2020-11-27 05:37

    Let's assume that you have some method like:

    public  T max (T a, T b) {
       ...
       //return maximum of a and b
    }
    

    If you know that there are only integers, longs and doubles can be passed as parameters then you can change method signature to:

    public  T max(double a, double b) {
       return (T)Math.max (a, b);
    }
    

    This will work for byte, short, integer, long and double.

    If you presume that BigInteger's or BigDecimal's or mix of floats and doubles can be passed then you cannot create one common method to compare all these types of parameters.

提交回复
热议问题