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?

62 Upvotes

94 comments sorted by

View all comments

Show parent comment

-3

u/re-thc Jan 19 '26

They can't in that 7.0000000001 can be the same as 7 or you can get 6.999999999. So you can't compare it to an Integer that won't have these irregularities.

10

u/JustAGuyFromGermany Jan 19 '26

But that's not the floating-point number. That's a string representation of a number. The problem you're describing is one of (base-10-)string representations of floating-point numbers, not of the floating-point numbers themselves.

For example: Remember that float is exactly embeddable into double, the IEEE standards are very precisely chosen to have this property. That doesn't mean that the same string representation gives you identical numbers when you evaluate them as float or double, because the string representations don't have this embedding property.

3

u/Nebu Jan 20 '26

7.0000000001 is not a valid IEEE-754 floating point value. I.e. you cannot create a float that has that value.

The closest valid value has binary representation 01000000111000000000000000000000, which represents the decimal value 7.

The next closest has binary representation 01000000111000000000000000000001, which represents the decimal value 7.0000005.

1

u/vytah Jan 20 '26

which represents the decimal value 7.0000005.

It actually represents 7.000000476837158203125. All those shorter representations you see are simply the shortest* decimal representations that unambiguously round to exactly one binary float.


*Finding the shortest decimal is difficult, so sometimes it's longer than needed.