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
4
u/dpx-infinity Jan 20 '26
Complex numbers are usually modeled as a pair of real numbers, the real and the imaginary parts. There is no useful and unsurprising way to implement intValue, longValue etc for them because of that. You can return some number, like amplitude, or the real part, or the imaginary part, but it wouldn’t make sense as these values do not “represent” the complex number in the same way as e.g. intValue represents the Double its is called on. While technically there is a bijection between reals and complex numbers, it is not very useful and probably not even computable.