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/vytah Jan 20 '26
That's not actually true. In Java,
equalson 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.0is truevalueOf(Double.NaN).equals(Double.NaN)is true,Double.NaN == Double.NaNis falseSimilarly, the implementation of Comparable for Float and Double defines a total order, so:
valueOf(-0.0).compareTo(+0.0) < 0is true,but
-0.0 < +0.0is 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:
Map<Double, _>has exactly those keys you put inhttps://docs.oracle.com/en/java/javase/25/docs/api//java.base/java/lang/Double.html#compareTo(java.lang.Double)