I recently discovered that the java.lang.Number class does not implement the Comparable interface. This became a problem while I was creating a custom list implementation that uses a type variable like , which led to issues when trying to use Collections.sort(list). It seems to me that implementing Comparable would be beneficial as it could prevent certain bugs and ensure stronger type guarantees. This brings me to my bigger question: are there any number types that aren't feasible to compare at all? Moreover, if there are some odd number types that can't extend from Number, wouldn't it make sense to create a subclass like NormalNumber that does provide Comparable functionality?
4 Answers
I wonder if complex numbers should even be considered part of the Number class. Plus, comparing floating-point numbers can get a bit complicated too!
Right, and remember that when mixing types like Integer with Rational in a list, things can easily go wrong because Integer doesn’t know how to compare with Rational.
The reason Number doesn't implement Comparable is that if it did, you'd either have to deal with all its subclasses or risk exceptions when you try comparing mismatched types. Alternatively, you’d need a generic approach which could break backwards compatibility since Number isn't set up this way right now. That's the tricky part!
Right! It’s like with Enums where they handle a similar scenario, but in this case, the absence of a self-referential operator in generics complicates things. There’s a lot of discussion around this in various dev circles, especially about generics in Java.
Exactly! Plus, using generics in their raw form is technically allowed due to generic erasure, so it wouldn't outright break code.
The short answer is that there isn't a universally correct way to order different Number classes. That's why making Number implement Comparable might lead to unexpected surprises in ordering, which is definitely not what you want.
Exactly! How would you even compare an Integer and a Double in a meaningful way?
You should also note that some classes, like AtomicInteger, are also not Comparable. This is largely because they manage concurrent modifications, and exposing a Comparable interface wouldn’t be suitable for them at all.
Haha, fair point! The number of edge cases here is definitely daunting, to say the least!

Haha, I get what you mean! Yes, complex numbers are tricky since they can't inherently implement methods like intValue(). But you're right about floating points; Double and Float are sortable... though NaN brings its own challenges.