Comparing the values of two generic Numbers

后端 未结 12 1763
小鲜肉
小鲜肉 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:31

    A working (but brittle) solution is something like this:

    class NumberComparator implements Comparator {
    
        public int compare(Number a, Number b){
            return new BigDecimal(a.toString()).compareTo(new BigDecimal(b.toString()));
        }
    
    }
    

    It's still not great, though, since it counts on toString returning a value parsable by BigDecimal (which the standard Java Number classes do, but which the Number contract doesn't demand).

    Edit, seven years later: As pointed out in the comments, there are (at least?) three special cases toString can produce that you need to take into regard:

    • Infinity, which is greater than everything, except itself to which it is equal
    • -Infinity, which is less than everything, except itself to which it is equal
    • NaN, which is extremely hairy/impossible to compare since all comparisons with NaN result in false, including checking equality with itself.

提交回复
热议问题