Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 java.lang.Number. How can I do that?

EDIT: I tried another workaround using TreeSets, 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 Lists, Collection.sort() will not accept my list due to bound mismatchs. Very unsatisfactory.

like image 801
b_erb Avatar asked Apr 21 '10 13:04

b_erb


People also ask

How do you compare numbers in Java?

To check two numbers for equality in Java, we can use the Equals() method as well as the == operator. Firstly, let us set Integers. Integer val1 = new Integer(5); Integer val2 = new Integer(5); Now, to check whether they are equal or not, let us use the == operator.

How do I compare generic types in C#?

To enable two objects of a generic type parameter to be compared, they must implement the IComparable or IComparable<T>, and/or IEquatable<T> interfaces. Both versions of IComparable define the CompareTo() method and IEquatable<T> defines the Equals() method.

How do you compare type T?

If you need to compare objects of type T for equality/inequality, you can use the IEquatable<T> interface.


1 Answers

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 );     } } 
like image 176
BennyBoy Avatar answered Sep 20 '22 09:09

BennyBoy