Why doesn't java.lang.Number implement Comparable?
Posted
by Julien Chastang
on Stack Overflow
See other posts from Stack Overflow
or by Julien Chastang
Published on 2009-01-26T17:32:52Z
Indexed on
2010/04/27
12:43 UTC
Read the original article
Hit count: 245
Does anyone know why java.lang.Number
does not implement Comparable
? This means that you cannot sort Number
s with Collections.sort
which seems to me a little strange.
Post discussion update:
Thanks for all the helpful responses. I ended up doing some more research about this topic.
The simplest explanation for why java.lang.Number does not implement Comparable is rooted in mutability concerns.
For a bit of review, java.lang.Number
is the abstract super-type of AtomicInteger
, AtomicLong
, BigDecimal
, BigInteger
, Byte
, Double
, Float
, Integer
, Long
and Short
. On that list, AtomicInteger
and AtomicLong
to do not implement Comparable
.
Digging around, I discovered that it is not a good practice to implement Comparable
on mutable types because the objects can change during or after comparison rendering the result of the comparison useless. Both AtomicLong
and AtomicInteger
are mutable. The API designers had the forethought to not have Number
implement Comparable
because it would have constrained implementation of future subtypes. Indeed, AtomicLong
and AtomicInteger
were added in Java 1.5 long after java.lang.Number
was initially implemented.
Apart from mutability, there are probably other considerations here too. A compareTo
implementation in Number
would have to promote all numeric values to BigDecimal
because it is capable of accommodating all the Number
sub-types. The implication of that promotion in terms of mathematics and performance is a bit unclear to me, but my intuition finds that solution kludgy.
© Stack Overflow or respective owner