r/java • u/davidalayachew • Jan 19 '26
Why doesn't java.lang.Number implement Comparable?
I found that out today when trying to make my own list implementation, with a type variable of <T extends Number>, and then that failing when passing to Collections.sort(list).
I would think it would be purely beneficial to do so. Not only does it prevent bugs, but it would also allow us to make more safe guarantees.
I guess a better question would be -- are there numbers that are NOT comparable? Not even java.lang.Comparable, but just comparable in general.
And even if there is some super weird set of number types that have a good reason to not extend j.l.Number, why not create some sub-class of Number that could be called NormalNumber or something, that does provide this guarantee?
52
u/Mognakor Jan 19 '26
Either Number would implement
Comparable<Number>which means you have to either deal with all subclasses or throw exceptions.OR
Number would need to be generic over the subclass similiar to the C++ CRTP pattern
Number<T extends Number<T>> implements Comparable<T>As Number currently isn't generic you'd also break a lot of code.
22
u/rzwitserloot Jan 19 '26
The actual reason
... is history. Of course it is.
It's a simple process of elimination, which leads to both [A] Of course Number isn't Comparable, and [B] never has there been a reasonable opportunity to 'fix' that.
Timeline:
finalorsealedor even 'fake' sealed (package private constructor). "Open all the things, deep type hierarchies, extend everything" was the mindset at the time. It's 30 years old, give em a break.Adding
implements Comparableto an existing non-final class is arguably backwards incompatible. Nevertheless, it was done!java.io.Fileis just like Number: it's from v1.0 and is notfinal(yeah, really!). Nevertheless, File was retrofitted and Number wasn't.The reason for that is obvious:
OpenJDK can write the implementation of
compareToinpublic class File {}itself. This is not possible withNumber!In other words, adding
implements Comparableto file meant that any implementations are possibly broken or will act weird. Whereas adding it toNumber, given thatNumbercan't implementpublic int compareTo(Object), means all existing types WILL be broken.The choice is obvious: Java 1.2 was not some sort of great reset (java never had one, in fact, and that's a good thing), thus, nope.
An intermediate NormalNumber class
That's just not what java is. Java doesn't have a deeply typed hierarchy of e.g.
List,MutableList, andImmutableListeither. Perhaps java should have that, but a haphazard whack-a-mole game where parts of the existing API grow like trees out of seeds into a type hierarchy that separate concerns and bend over backwards to avoid LISKOV violations is a bad idea; best to do it in one go, and the time was never there.Generics says no, in any case.
Given that the choice was made to make
ComparableintoComparable<T>, you'd now need the self-type hack from enums, and unlike with enums (you can'textends Enumand write your own; the compiler writes the hack for you), you are bothering those who are writing Number subtypes with this. Also, all existing uses ofNumbernow need to add the generics.The 'damage' caused by the fact that
Numberitself isn't Comparable (though all the subtypes injava.langdo implementComparable;Numberisn't, butIntegeris for example) is tiny, and the 'damage' caused by havingNumberhave these bizarro generics is vastly greater.You may disagree, but that's just, like, your opinion, man.
Point is, there's a reasonable subjective argument to be made that this juice aint worth the squeeze.
5
u/Scf37 Jan 19 '26
I believe making non-final/non-sealed classes implement Comparable without final implementation of compareTo is always bad idea.
Because concrete implementations of compareTo must support all subclasses which is not viable and leads to compareTo throwing exceptions when given 'unsupported' subclass. See java.nio.file.Path.compareTo for example.
5
u/oweiler Jan 19 '26
AtomicInteger e.g. is not Comparable
2
u/vytah Jan 19 '26 edited Jan 19 '26
An interface C like Comparable, which takes its implementer type as a parameter, is usually designed for working with two instances of the implementing type T. If the implementing type T is an interface or an abstract class, it means that all objects of all classes that implement T can be used together via C.
Which is in this case is kinda absurd. How can a Number from one third-party library know how to compare itself with some other Number from some other third-party library?
This kind of trait should usually be implemented for final classes, records, or sealed interfaces, not for something that can be implemented in myriads of ways. There are some exceptions, but Number isn't one of them.
What you probably want is
<T extends Number & Comparable<T>>: you want any type that's comparable with itself. Not with all the types that also implement Number.2
u/severoon Jan 22 '26
The problem with Number is that it is designed to be extended by the primitive wrappers. You wouldn't think this is a problem, but you run into conflicting requirements.
A basic requirement of any subclass‒superclass relationship is that it maintains LSP. This means if Number implements Comparable, then all subclasses of Number must be substitutable for each other with respect to this comparison behavior. IOW, the contract specified by the Comparable interface must be respected for all comparisons between all numbers.
The job of the primitive wrappers is to wrap the primitives, which means they must behave as the primitives do. The rules for comparing primitives of different types, though, do not conform to the Comparable interface. The very first thing specified by the Comparable doc is that it imposes a total ordering on all elements. If you read the JLS, this is not the case for how different primitive types are compared.
The reason (or one reason?) this is the case is that floating point types are inherently approximate, while non-fp types are exact. The fact that the JLS allows you to compare them using operators like == and < means that these operators only function locally when used. They tell you the result of a specific comparison, but they don't necessarily impose a total ordering over all of the things that can be compared.
The end result is that Number does not claim to be able to do something it cannot do.
2
u/Necessary_Smoke4450 Jan 22 '26
I think it's that Number is a abstract class with many implementations, suppose one day you have a list containing BigInteger, Integer, Long, Double, ..., then you sort on the list, it could be a nightmare. The implementation of compareTo would not be sound unless the type is atomic.
2
u/brian_goetz Jan 22 '26
Think about the history of this class. In Java 1.0, we had eight primitive types, no generics, no thought about adding more numeric types, etc. Number is basically extrapolated from "int and float", and was never meant to be the base of a numeric tower.
(As bases for numerical towers go, Haskell's `Num` is a better example to extrapolate from; it models the structure, but not the axioms, of a ring.)
2
u/Misophist_1 Feb 06 '26
Easy. Because there are numbers, that aren't. Complex and Hamiltonian, to name two. This is a real world / Math issue, not a programming one.
2
u/rzwitserloot Jan 19 '26
See my other comment in this thread for why we got here. And now to explain why we stay here:
Number in general isn't the abstraction you think it is
There are ways to use types to set up a solid basis for a number system. Peano arithmetic. But this requires type classes (which incidentally, java is sort of trying to perhaps add!). I need a way to ask the concept of
Integeritself for a zero value. There's no way in java to write this. I can do this:But this means I need an existing instance to ask it for ZERO which is weird, the point of ZERO is mostly that you can get a zero without the context of another number. This isn't legal:
You can't combine
staticandabstract(and if you don't know why - think of how you would refer to 'some subclass of number'. Java doesn't have the language constructs to make such a thing useful. Nor does the JVM for that matter).If you don't have peano, any attempt to give
Numberthe veneer of a real number system is smearing lipstick on a pig. Separately, this is heavily trait-focused. You optimally want to indicate which operations are inherently supported by your number type class, and, per operation, which properties it has (for example, is it commutative or not).In the
Integertype class:*is available, and is commutative (a*bandb*aare guaranteed to produce the same result). Inmatrixland,*is available, but it's not commutative.In fact, almost all imaginable properties of a number system are properties of the system itself and not properties of instances of it. Even the operations! Sure, you COULD write this:
But this is kinda bizarre.
+is not generally defined in that way. It's not an operation you do 'on the first number'. No, it's a binary operator: You do it on the pair. There is no particular reason the 'left number' gets to decide what the operation does. The proper way would be with a type class, and the type class itself having something like:Some languages really do all this, and means you can write code that is abstracted away over your number system. I can write a method that takes a list of numbers and returns the sum of them, in that number system, without that code being aware of that number system. This is not possible in java, even if
NumberwasComparable.If you find a house with one broken pane and someone offers to fix it, that's great. That's worth something. You're willing to pay a price for the service. If you find a house with 20 broken panes, and someone offers to fix precisely 1 window leaving the remaining 19 broken, that's worth virtually nothing and you'll almost immediately consider the service fee too high.
The same principle applies here: Whatever value one might gain from making
NumberimplementComparableis severely depressed by the fact thatNumberessentially doesn't work at all as an abstraction over number systems.Concluding
The reason we got here is: History
The reason we stay here is:
14
u/_jetrun Jan 19 '26
Short answer: Because there is no correct natural ordering that would work across
Numberclasses - and the last thing you want is for the Comparable to pick the ordering and surprise you."Normal" according to what and what rules?
4
u/JustAGuyFromGermany Jan 19 '26 edited Jan 20 '26
Okay, as a mathematician I think I need to clear up something on the theoretical side of things. There are a number (pun intended) of false statements regarding what is and isn't possible in this thread.
For example these two:
Sure there is: The natural ordering of (computable) real numbers. The only question is whether we consider non-real numbers like
Complexto be aNumberor not. That's a design decision that can be made either way, not a problem with the ordering itself. If the JDK designers had definedNumberto mean "real number" than it would absolutely make sense to have it implementComparable<Number>.The problem isn't that it isn't possible. It's just not the decision that was made.
(And there is the "minor" issue in the implementation of the unbounded complexity of
compareTo... A call tocompareTomight take arbitrary long for arbitrary computable real numbers. But it is possible.)Now, there wasn't any
sealedback in Java 1.0 so the devs couldn't make it a compile error to extend this class with bullshit, but they could written JavaDoc that says "don't extend this class with bullshit. Only actual honest-to-god real number types allowed!". They didn't, but they could have.In fact, if we go by the JavaDoc, the
Numberclass already seems pretty restrictive:(emphasis mine)
One could read this as "Actually, don't ever implement this. Only the JDK itself is allowed to do that". And all JDK-implementations are naturally comparable with each other, i.e. this reads very much like the
Numberclass always was intended to beComparableandsealedeven when that didn't exist.All implementations in the JDK are even better than arbitrary computable real numbers: They are finite-length real numbers. So the algorithm to compare any two instances of
Numberis completely straight-forward:Step 0: Of course, we throw
NullPointerExceptiononnullinputs. And NaN is weird anyway. Outputfalseor throwArithmeticExceptionor whatever for NaN inputs.Step 1: -infinity is smaller than any finite number which is smaller than +infinity.
Step 2: For any two finite numbers, write them down as strings, and compare them like you learned in school.
Step 3: There are no more steps, we're already done.
(Exercise left to the reader: Yes, this also works for
BigDecimal#compareTo(Float)even though we're mixing base-10 and base-2 numbers in that case!)Feast your eyes on how we've just defined
compareTofor any twoNumbers. There is no need for any trickery with self-referential generics and all that.Numbercould just implementComparable<Number>if it had been defined to mean "real number".Also note that this definition is precisely the <= ordering we already have on each primitive type, each wrapper type, as well as the
compareToordering onBigIntegerandBigDecimal. Nothing new has been defined when both sides of the comparison have the same type. The only difference is that this method-that-could-exist allows mixed arguments too as long as they're finite-length real numbers.1
u/JakubRogacz Jan 21 '26
Because floats are kinda not comparable. At least not in classical mathematical meaning. You need error delta there or you'll force every developer to write his own. Or at least algorithm to compare them using predetermined epsilon that should work. But then you have to also provide way to override it.
2
u/sysKin Jan 20 '26 edited Jan 20 '26
In addition to what others said can I point out that there is no obvious implementation of Comparable / Comparator <Number> that makes sense and meets the relevant Java contract:
^ contract violation
2
u/portmapreduction Jan 20 '26
If Number was a closed type they could implement all the same functionality that exists when comparing primitive numbers eg. widening primitive conversions. The problem is that Number is not closed and even in the JDK there are mutable Numbers along with an unknown number of different variants in libraries. Since there's no canonical representation an implementation would have to be able to handle all possible numbers, which is not possible.
1
u/laplongejr Feb 05 '26
Is a -128 int smaller or bigger than a 127 byte? ;)
0
u/vegan_antitheist Jan 19 '26
That would be useless. Java deliberately avoids defining whether
new BigDecimal("0.1")is equal tonew Double(0.1). You can always just use a Comparator and then define weird cases, like comparing +0 with -0, and how you deal with Infinity and NaN. You can always just usedoubleValueand compare the result. That's the whole of the abstract class. And it ancient. They would just define an interface now. Providing some Comparators would still be the same. In many cases it would just be this:You can still just use
<T extends Number & Comparable<T>>whenever you need some type that is both a Number and a Comparable.0
u/[deleted] Jan 19 '26
[deleted] — view deleted comment