Nullable 比較

9月3日に、NULL可能性考慮のequals を書いたが、compareTo があまりにも不完全なので書き直した。

/**
 * nullable compareTo.
 * NULLの可能性のあるプリミティブclass及び Comparable の compareTo.
 * 以下、null は各々に置き換えられて compareTo が実行される
 *   Integer    null  → 0
 *   Long       null  → (long)0
 *   Short      null  → (short)0
 *   Character  null  → (char)0x0
 *   Byte       null  → (byte)0
 *   Float      null  →  new Float(0)
 *   Double     null  → (double)0
 *   Boolean    null  → false
 *
 * String s1="a"; String s2=null;
 * Pace.compareTo(s1,s2) の結果は、> 0 である
 *
 * Integer i1=new Integer("1"); Integer i2=null;
 * Pace.compareTo(i1,i2) の結果は、> 0 である
 */

@SuppressWarnings("unchecked")
public static <T> int compareTo(T t1,T t2){
   if (t1 instanceof Integer || t2 instanceof Integer){
      Integer i1 = (Integer)(t1==null ? 0 : t1);
      Integer i2 = (Integer)(t2==null ? 0 : t2);
      return i1.compareTo(i2);
   }else if(t1 instanceof Long || t2 instanceof Long){
      Long l1 = (Long)(t1==null ? (long)0 : t1);
      Long l2 = (Long)(t2==null ? (long)0 : t2);
      return l1.compareTo(l2);
   }else if(t1 instanceof Short || t2 instanceof Short){
      Short s1 = (Short)(t1==null ? (short)0 : t1);
      Short s2 = (Short)(t2==null ? (short)0 : t2);
      return s1.compareTo(s2);
   }else if(t1 instanceof Character || t2 instanceof Character){
      Character c1 = (Character)(t1==null ? (char)0x0 : t1);
      Character c2 = (Character)(t2==null ? (char)0x0 : t2);
      return c1.compareTo(c2);
   }else if(t1 instanceof Byte || t2 instanceof Byte){
      Byte b1 = (Byte)(t1==null ? (byte)0 : t1);
      Byte b2 = (Byte)(t2==null ? (byte)0 : t2);
      return b1.compareTo(b2);
   }else if(t1 instanceof Float || t2 instanceof Float){
      Float f1 = (Float)(t1==null ? new Float(0) : t1);
      Float f2 = (Float)(t2==null ? new Float(0) : t2);
      return f1.compareTo(f2);
   }else if(t1 instanceof Double || t2 instanceof Double){
      Double d1 = (Double)(t1==null ? (double)0 : t1);
      Double d2 = (Double)(t2==null ? (double)0 : t2);
      return d1.compareTo(d2);
   }else if(t1 instanceof Boolean || t2 instanceof Boolean){
      Boolean b1 = (Boolean)(t1==null ? false : t1);
      Boolean b2 = (Boolean)(t2==null ? false : t2);
      return b1.compareTo(b2);
   }else if(t1==null && t2==null){
      return 0;
   }else if(t1==null){
      return -1;
   }else if(t2==null){
      return 1;
   }else if(t1 instanceof Comparable && t2 instanceof Comparable){
      Comparable<T> c1 = (Comparable<T>)t1;
      return c1.compareTo(t2);
   }
   throw new IllegalArgumentException("parameter must be primitive or Comparable");
}