How to sort a List<Number>
?
Example:
List<Number> li = new ArrayList<Number>(); //list of numbers
li.add(new Integer(20));
li.add(new Double(12.2));
li.add(new Float(1.2));
How to sort a List<Number>
?
Example:
List<Number> li = new ArrayList<Number>(); //list of numbers
li.add(new Integer(20));
li.add(new Double(12.2));
li.add(new Float(1.2));
Simple answer: You can't. A proprietary Number implementation may have higher precision or a larger value range than what is available through the getXXX() methods defined for the actual value in the Number interface.
You'll need a solution for
null
values, because they may be in the collection - you can't create a collection of objects that doesn't takenull
.So you could check for
null
and throwIllegalArgumentException
- with the sideeffect, that you won't be able to sort "polluted" lists and have to handle those exceptions at runtime.Another idea is to convert a
null
to some kind of number. I've shown this approach (based on you own solution from your own answer) by converting anynull
toDouble.NaN
by convention. You could also consider converting them to0
or toDouble.POSITIVE_INFINITY
orDouble.NEGATIVE_INFINITY
if you wantnull
values sorted to the far ends.Further Information
Here's some code that shows how thoses special values are handled by "default":
The result (with no
null
addded) is:As jarnbjo points out in his answer, there is no way to implement a
Comparator<Number>
correctly, as instances ofNumber
may very well represent numbers larger thanDouble.MAX_VALUE
(and that's unfortunately as far as theNumber
interface allows us to "see"). An example of aNumber
larger thanDouble.MAX_VALUE
isThe solution below however, handles
Byte
s,Short
s,Integer
s,Long
s,Float
s andDouble
sArbitrary large
BigInteger
sArbitrary large
BigDecimal
sInstances of
{Double, Float}.NEGATIVE_INFINITY
and{Double, Float}.POSITIVE_INFINITY
Note that these should always come before/after any
BigDecimal
even though theBigDecimal.doubleValue
may returnDouble.NEGATIVE_INFINITY
orDouble.POSITIVE_INFINITY
null
elementsA mixture of all of the above, and
Unknown implementations of
Number
that also implementsComparable
.(This seems to be a reasonable assumption since all
Number
s in the standard API implements Comparable.)Here is a small test program (here is an ideone.com demo):
...which prints (I removed a few zeros):
try my java sorting algorithm:
Have a look at Andreas_D's answer for explanation.In the above code all null values and +Infinity values are handled such that they move to the end.
Update 1:
As jarnbjo and aioobe points out a flaw in the above implementation.So I thought it's better to restrict the implementation's of Number.
Update 2:
Using guava's constrained list (will not allow entry of null or unsupported type to list):