Re: Discussion of why java.lang.Number does not implement Comparable
Twisted wrote:
On Jul 28, 11:54 am, Patricia Shanahan <p...@acm.org> wrote:
....
However, to make Number implement Comparable we would need a general
approach to comparing that does not depend on writing special code for
every pair of Number subclasses.
Here's a challenge for those who want to make Number implement
Comparable<Number>. Write the API documentation for the compareTo
method. Tell me what I have to do if I am writing a new Number subclass
in order to conform to the contract.
The simplest most general way is to convert to BigDecimal and punt to
BigDecimal.compareTo, with precision decided by something (perhaps
something new) in the way of a MathContext-like entity. It couldn't be
passed to the compareTo method obviously so it would have to be a
threadlocal or something (a singleton would cause problems if distinct
threads did simultaneous math and wanted distinct precisions).
This could lead to some very strange effects. You could have two
numbers, x and z, that are different according to the comparison rules
for their own class, but that match to the Number comparison precision.
x.compareTo(z) would be non-zero. However, there could be a third
Number, y, of a different Number subclass, such that y.compareTo(x) and
y.compareTo(z) are both zero.
Fortunately I think putting heterogeneous Numbers into a sorted
collection is really damn rare.
The killer argument for not having Number implement Comparable.
If a given Number subclass has a reasonable total order it can implement
its own intra-class comparison. For example, Double implements
Comparable<Double>, and BigDecimal implements Comparable<BigDecimal>.
If there is a need, and a good implementation, for a total order on a
collection containing a couple of different Number subclasses, one could
write a Comparator that handles that combination of classes, using
appropriate special rules.
I think this approach deals with all the real cases, without opening
up the general Number comparison can of worms.
Patricia