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

Show parent comment

1

u/vytah Jan 20 '26

because equals is defined in terms of this numerical value for floating point numbers (i.e. (-0.0).equals(+0.0) == true

That's not actually true. In Java, equals on floating-point types compares bit representation, not numeric value. For value-based comparisons as defined in the IEEE standard, use operators.

valueOf(-0.0).equals(+0.0) is false,
-0.0 == +0.0 is true

valueOf(Double.NaN).equals(Double.NaN) is true,
Double.NaN == Double.NaN is false

Similarly, the implementation of Comparable for Float and Double defines a total order, so:

valueOf(-0.0).compareTo(+0.0) < 0 is true,
but -0.0 < +0.0 is false.

NaNs and infinities also have a defined order (the total order goes negative NaNs, negative infinity, negative numbers, -0.0, +0.0, positive numbers, positive infinity, positive NaNs; most NaNs you'll encounter will be positive)

This way:

  • you can sort an array of floats without getting IllegalArgumentException for comparator contract violations
  • you can rely on the substitution property of equality: a=b ⇒ f(a)=f(b)
  • you can be sure that Map<Double, _> has exactly those keys you put in

https://docs.oracle.com/en/java/javase/25/docs/api//java.base/java/lang/Double.html#compareTo(java.lang.Double)

2

u/JustAGuyFromGermany Jan 20 '26

Goddamnit, I even looked it up and still got it mixed up. == is the numerical equivalence, equals is the odd one.

Still, my larger point remains: A reasonable comparison is possible by using numerical comparison. The devs just decided against it.