/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
@SuppressWarnings("unchecked")
class NumberComparator implements Comparator<Number> {
// Special values that are treated as larger than any other.
private final static List<?> special =
private final static List<?> largest =
private final static List<?> smallest =
// Handle special cases (including null)
if (special.contains(n1)) return 1;
if (special.contains(n2)) return -1;
if (largest.contains(n1) || smallest.contains(n2)) return 1;
if (largest.contains(n2) || smallest.contains(n1)) return -1;
// Promote known values (Byte, Integer, Long, Float, Double and
// BigInteger) to BigDecimal, as this is the most generic known type.
if (bd1 != null && bd2 != null)
return bd1.compareTo(bd2);
// Handle arbitrary Number-comparisons if o1 and o2 are of same class
// and implements Comparable.
if (n1 instanceof Comparable<?> && n2 instanceof Comparable<?>)
try {
}
// If the longValue()s differ between the two numbers, trust these.
int longCmp
= ((Long) n1.
longValue()).
compareTo(n2.
longValue()); if (longCmp != 0)
return longCmp;
// Pray to god that the doubleValue()s differ between the two numbers.
int doubleCmp
= ((Double) n1.
doubleValue()).
compareTo(n2.
doubleValue()); if (doubleCmp != 0)
return longCmp;
// Die a painful death...
"Cannot compare " + n1 + " with " + n2);
}
// Convert known Numbers to BigDecimal, and the argument n otherwise.
return null;
}
}
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main
(String[] args
) { List<Number> li = new ArrayList<Number>();
// Add an Integer, a Double, a Float, a Short, a Byte and a Long.
li.add(20); li.add((short) 17);
li.add(12.2); li.add((byte) 100);
li.add(0.2f); li.add(19518926L);
// A custom Number
li.add(new BoolNumber(1));
li.add(new BoolNumber(0));
// Add two BigDecimal that are larger than Double.MAX_VALUE.
li.add(largeDec/*.multiply(BigDecimal.TEN)*/);
// Add two BigInteger that are larger than Double.MAX_VALUE.
// ...and just for fun...
li.add(null);
}
static class BoolNumber
extends Number { boolean b;
public BoolNumber(int i) { b = i != 0; }
public double doubleValue() { return b ? 1d : 0d; }
public float floatValue() { return b ? 1f : 0f; }
public int intValue() { return b ? 1 : 0; }
public long longValue() { return b ? 1L : 0L; }
public String toString
() { return b
? "1" : "0"; } }
}