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?
View all comments
Show parent comment
1
u/manifoldjava Jan 19 '26
Nicely written.
I've always wondered why this wasn't part of foundational Java. See discussion: Class is not fully OOP, should it be?
manifold provides this via
@Self. It accomplishes both less and more than what recursive types offer without the ugly consequences. Don't know why this feature hasn't surfaced in Java all these years.The behavior of the operation isn't any clearer with a type class. The rules of the operation dictate behavior that both
SELF plus(SELF other)andtype Operator<SELF> plus()adhere to. Type class buys the potential to have multiple implementations. But then Plus could be an interface supplied with dependency injection just as well, and with more clarity and less ceremony. But Java lords have always talked the talk wrt interface composition, but never seemed to walk the walk - no delegation, no traits, etc. But I digress.What is more interesting is
class A{ C times(B other){...} }.