Skip navigation.

BlogtimeException

By Behrang Saeedzadeh (the 5th incarnation)

Posts tagged with "Sorting"

Number Comparison Dilemma in Java

, , ,

Recently I needed to sort a collection of Number objects (i.e Integers, Doubles, Longs, etc.) in a clean and concise manner somewhere deep within the code-base of the project component of my thesis. Here, by "clean and concise", I mean without lots of ugly castings, ifs, switches, etc.

At first I thought that the Number class implements the Comparable interface in a way that makes it possible to sort a collection of heterogenous Number objects. To my surprise, it turned out that the Number class does not implement the Comparable and instead, implementing Comparable is delegated to its subclasses. So an Integer is only comparable to an Integer, a Double to a Double, and so on.

It turns out that this is not a new problem and it has hit a lot of other programmers as well. In short, there's not a concise and clean solution to this problem. I searched through the Web and I came up with these two links among others that discuss this very problem and I thought it worths to share it here:

If you have any thoughts, ideas, or solutions please care to write about them in the comments.