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 java.lang.Number
. How can I do that?
EDIT: I tried another workaround using TreeSet
s, which actually worked with natural ordering (of course it works, all subclasses of Number
implement Comparable
except for AtomicInteger and AtomicLong). Thus I'll lose duplicate values. When using List
s, Collection.sort()
will not accept my list due to bound mismatchs. Very unsatisfactory.
Note: The
instanceof
check isn't necessarily needed - depends on how exactly you want to compare them. You could of course simply always use.doubleValue()
, as every Number should provide the methods listed here.Edit: As stated in the comments, you will (always) have to check for BigDecimal and friends. But they provide a
.compareTo()
method:After having asked a similar question and studying the answers here, I came up with the following. I think it is more efficient and more robust than the solution given by gustafc:
If your Number instances are never Atomic (ie AtomicInteger) then you can do something like:
This is since all non-Atomic
Number
s implement ComparableEDIT:
This is costly due to reflection: I know
EDIT 2:
This of course does not take of a case in which you want to compare decimals to ints or some such...
EDIT 3:
This assumes that there are no custom-defined descendants of Number that do not implement Comparable (thanks @DJClayworth)
This should work for all classes that extend Number, and are Comparable to themselves. By adding the & Comparable you allow to remove all the type checks and provides runtime type checks and error throwing for free when compared to Sarmun answer.
You can simply use
Number's doubleValue()
method to compare them; however you may find the results are not accurate enough for your needs.