开发者

how to compare two objects in generic implementation?

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜