r/java • • 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?

64 Upvotes

94 comments sorted by

View all comments

Show parent comment

1

u/davidalayachew Jan 22 '26

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.

There's the missing detail!

So, my entire post is based upon a false assumption. It sounds like you are saying that, if we had sealed types back in 1995, that Java would have made Number a sealed type? Well, maybe Java 5, as that is when the wrappers came.

2

u/brian_goetz Jan 22 '26

I'm not sure what they would have done. But it is not an abstraction that captures very much about number-ness other than "converts to/from the built in numeric types."

1

u/davidalayachew Jan 22 '26

But it is not an abstraction that captures very much about number-ness other than "converts to/from the built in numeric types."

Yeah, and I was hoping I could enhance it to include more info. And if not that, then maybe adding a sub-type that could do that.

How do you feel about the NormalNumber suggestion? That shouldn't conflict with history. I'd have to modify it to be NormalNumber<T extends NormalNumber<T>>. But that should work, right? Then we can put all sorts of number-like things there.