开发者

how to compare two objects in generic implementation?

开发者 https://www.devze.com 2023-04-07 19:06 出处:网络
I have a generic class which will be Long, Float, Integer and开发者_StackOverflow String types. In the cases of Number (Long, Float and Integer), I want to compare two of them to see which one is bigg

I have a generic class which will be Long, Float, Integer and开发者_StackOverflow 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?


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消