5YrsLaterDBA
5YrsLaterDBA

Reputation: 34750

how to compare two objects in generic implementation?

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

Answers (3)

Costi Ciudatu
Costi Ciudatu

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

mcfinnigan
mcfinnigan

Reputation: 11638

the easiest way would be to implement the Comparable interface in your subclasses.

Upvotes: 1

Pintobean77
Pintobean77

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

Related Questions