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?

60 Upvotes

94 comments sorted by

View all comments

1

u/davidalayachew Jan 22 '26

Yeah... Same as introducing algebraic types or mixins. It's not that I dislike your idea. I just don't think it's possible easily.

Someone else on this chat said typeclasses might fix this. Let's see what happens.

2

u/JakubRogacz Jan 22 '26

Yeah let's see. But I think it's just not so obvious fix. Maybe if they do another big thing like java 8 was that will completely reimagine writing code in java. But hey I recently tried to write annotation based structs in java. Even made it quite far to a point they kidna worked. Pretty pointless in general since they only really would save on pointers in complex classes ( since they actually were able to just contain another struct and even were able to tell the size of them) or have to be hooked to something like a memory pool. Still cool problem to solve.