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.
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.
class NumberComparator<T extends Number & Comparable> implements Comparator<T> {
public int compare( T a, T b ) throws ClassCastException {
return a.compareTo( b );
}
}