Reputation: 34750
I have a generic class which will be Long
, Float
, Integer
and String
types. In the cases of Number
(Long
, Float
and Integer
), I want to compare two of them to see which one is bigger or smaller. Is it possible?
Upvotes: 2
Views: 1586
Reputation: 38195
If you only need that for numbers, just compare them as "values" with the same data type (the proper methods for this are provided by the java.lang.Number
class). So you can do:
Double.compare( number1.doubleValue(), number2.doubleValue() )
where number1
and number2
are different types of numbers.
The Comparable
interface is implemented by all the numeric primitive wrappers but they can only compare numbers of the same type. For instance Integer
implements Comparable<Integer>
, so the compareTo
method won't accept other numeric types.
Upvotes: 1
Reputation: 11638
the easiest way would be to implement the Comparable
interface in your subclasses.
Upvotes: 1
Reputation: 1415
Its possible with a moderately complex Comparator implementation and liberal use of the 'instanceof' keyword.
http://download.oracle.com/javase/6/docs/api/java/util/Comparator.html
Upvotes: 1