b_erb b_erb - 1 year ago 80
Java Question

Comparing the values of two generic Numbers

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 don't know the exact type yet, I only know that it will be a subtype of
. How can I do that?

EDIT: I tried another workaround using
s, which actually worked with natural ordering (of course it works, all known subclasses of
). Thus I'll lose duplicate values. When using
will not accept my list due to bound mismatchs. Very unsatisfactory.

Answer Source

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

class NumberComparator implements Comparator<Number> {

    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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download